This issue is got resolved after adding network service role.
CERTIFICATE ISSUES
Error :Keyset does not exist means System might not have access to private key
Error :Enveloped data …
Step 1:Install certificate in local machine not in current user store
Step 2:Run certificate manager
Step 3:Find your certificate in the local machine tab and right click manage privatekey and check in allowed personnel following have been added:
a>Administrators
b>yourself
c>'Network service'
And then provide respective permissions.
## You need to add 'Network Service' and then it will start working.
I have a small plugin that handles this.
It's called waitForImages and it can handle img
elements or any element with a reference to an image in the CSS, e.g. div { background: url(img.png) }
.
If you simply wanted to load all images, including ones referenced in the CSS, here is how you would do it :)
$('body').waitForImages({
waitForAll: true,
finished: function() {
// All images have loaded.
}
});
In order to pause the streaming in fast-csv you can do the following:
let csvstream = csv.fromPath(filePath, { headers: true })
.on("data", function (row) {
csvstream.pause();
// do some heavy work
// when done resume the stream
csvstream.resume();
})
.on("end", function () {
console.log("We are done!")
})
.on("error", function (error) {
console.log(error)
});
You need formulas to convert latitude and longitude to rectangular coordinates. There are a great number to choose from and each will distort the map in a different way. Wolfram MathWorld has a good collection:
http://mathworld.wolfram.com/MapProjection.html
Follow the "See Also" links.
I need to catch pressing Enter on a keyboard with TextWatcher. But I found out that all numeric keyboards android:inputType="number" or "numberDecimal" or "numberPassword" e.t.c. don't allow me to catch Enter when user press it.
I tried android:digits="0123456789\n"
and all numeric keyboards started to work with Enter and TextWatcher.
So my way is:
android:digits="0123456789\n"
android:inputType="numberPassword"
plus editText.setTransformationMethod(null)
Thanks to barmaley and abhiank.
In order to get the PHP output into the HTML file you need to either
You can use MutationObserver to track attribute changes including data-*
changes. For example:
var foo = document.getElementById('foo');_x000D_
_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
console.log('data-select-content-val changed');_x000D_
});_x000D_
observer.observe(foo, { _x000D_
attributes: true, _x000D_
attributeFilter: ['data-select-content-val'] });_x000D_
_x000D_
foo.dataset.selectContentVal = 1;
_x000D_
<div id='foo'></div>_x000D_
_x000D_
Don't use wait()
, use either android.os.SystemClock.sleep(1000);
or Thread.sleep(1000);
.
The main difference between them is that Thread.sleep()
can be interrupted early -- you'll be told, but it's still not the full second. The android.os
call will not wake early.
Using the re
module:
import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And so\tshould this') # And_so_should_this
Unless you have multiple spaces or other whitespace possibilities as above, you may just wish to use string.replace
as others have suggested.
Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.
Copy/Paste Code below:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date
End Sub
Good luck...
To sort a dictionary and keep it functioning as a dictionary afterwards, you could use OrderedDict from the standard library.
If that's not what you need, then I encourage you to reconsider the sort functions that leave you with a list of tuples. What output did you want, if not an ordered list of key-value pairs (tuples)?
Are you looking for the SQL used to generate a table? For that, you can query the sqlite_master
table:
sqlite> CREATE TABLE foo (bar INT, quux TEXT);
sqlite> SELECT * FROM sqlite_master;
table|foo|foo|2|CREATE TABLE foo (bar INT, quux TEXT)
sqlite> SELECT sql FROM sqlite_master WHERE name = 'foo';
CREATE TABLE foo (bar INT, quux TEXT)
Nice one, big thanks to Max.
I've wrapped the functionality in his answer into jQuery if anyone wants to use it.
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
Just call moment as a function without any arguments:
moment()
For timezone information with moment, look at the moment-timezone
package: http://momentjs.com/timezone/
NOTE: This post ended up being far more detailed and therefore off topic, I apologize.
That being said my peers read it and believe it is valuable 'somewhere'. This thread is not the place. I would appreciate your feedback on where this should go (I am new to the site).
Anyway this is the C# version in .NET 3.5 which is amazing in that it works on any collection type using the defined semantics. This is a default measure (reuse!) not performance or CPU cycle minimization in most common dev scenario although that never seems to be what happens in the real world (premature optimization).
*** Extension method working over any collection type and taking an action delegate expecting a single value of the type, all executed over each item in reverse **
Requres 3.5:
public static void PerformOverReversed<T>(this IEnumerable<T> sequenceToReverse, Action<T> doForEachReversed)
{
foreach (var contextItem in sequenceToReverse.Reverse())
doForEachReversed(contextItem);
}
Older .NET versions or do you want to understand Linq internals better? Read on.. Or not..
ASSUMPTION: In the .NET type system the Array type inherits from the IEnumerable interface (not the generic IEnumerable only IEnumerable).
This is all you need to iterate from beginning to end, however you want to move in the opposite direction. As IEnumerable works on Array of type 'object' any type is valid,
CRITICAL MEASURE: We assume if you can process any sequence in reverse order that is 'better' then only being able to do it on integers.
Solution a for .NET CLR 2.0-3.0:
Description: We will accept any IEnumerable implementing instance with the mandate that each instance it contains is of the same type. So if we recieve an array the entire array contains instances of type X. If any other instances are of a type !=X an exception is thrown:
A singleton service:
public class ReverserService { private ReverserService() { }
/// <summary>
/// Most importantly uses yield command for efficiency
/// </summary>
/// <param name="enumerableInstance"></param>
/// <returns></returns>
public static IEnumerable ToReveresed(IEnumerable enumerableInstance)
{
if (enumerableInstance == null)
{
throw new ArgumentNullException("enumerableInstance");
}
// First we need to move forwarad and create a temp
// copy of a type that allows us to move backwards
// We can use ArrayList for this as the concrete
// type
IList reversedEnumerable = new ArrayList();
IEnumerator tempEnumerator = enumerableInstance.GetEnumerator();
while (tempEnumerator.MoveNext())
{
reversedEnumerable.Add(tempEnumerator.Current);
}
// Now we do the standard reverse over this using yield to return
// the result
// NOTE: This is an immutable result by design. That is
// a design goal for this simple question as well as most other set related
// requirements, which is why Linq results are immutable for example
// In fact this is foundational code to understand Linq
for (var i = reversedEnumerable.Count - 1; i >= 0; i--)
{
yield return reversedEnumerable[i];
}
}
}
public static class ExtensionMethods
{
public static IEnumerable ToReveresed(this IEnumerable enumerableInstance)
{
return ReverserService.ToReveresed(enumerableInstance);
}
}
[TestFixture] public class Testing123 {
/// <summary>
/// .NET 1.1 CLR
/// </summary>
[Test]
public void Tester_fornet_1_dot_1()
{
const int initialSize = 1000;
// Create the baseline data
int[] myArray = new int[initialSize];
for (var i = 0; i < initialSize; i++)
{
myArray[i] = i + 1;
}
IEnumerable _revered = ReverserService.ToReveresed(myArray);
Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));
}
[Test]
public void tester_why_this_is_good()
{
ArrayList names = new ArrayList();
names.Add("Jim");
names.Add("Bob");
names.Add("Eric");
names.Add("Sam");
IEnumerable _revered = ReverserService.ToReveresed(names);
Assert.IsTrue(TestAndGetResult(_revered).Equals("Sam"));
}
[Test]
public void tester_extension_method()
{
// Extension Methods No Linq (Linq does this for you as I will show)
var enumerableOfInt = Enumerable.Range(1, 1000);
// Use Extension Method - which simply wraps older clr code
IEnumerable _revered = enumerableOfInt.ToReveresed();
Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));
}
[Test]
public void tester_linq_3_dot_5_clr()
{
// Extension Methods No Linq (Linq does this for you as I will show)
IEnumerable enumerableOfInt = Enumerable.Range(1, 1000);
// Reverse is Linq (which is are extension methods off IEnumerable<T>
// Note you must case IEnumerable (non generic) using OfType or Cast
IEnumerable _revered = enumerableOfInt.Cast<int>().Reverse();
Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));
}
[Test]
public void tester_final_and_recommended_colution()
{
var enumerableOfInt = Enumerable.Range(1, 1000);
enumerableOfInt.PerformOverReversed(i => Debug.WriteLine(i));
}
private static object TestAndGetResult(IEnumerable enumerableIn)
{
// IEnumerable x = ReverserService.ToReveresed(names);
Assert.IsTrue(enumerableIn != null);
IEnumerator _test = enumerableIn.GetEnumerator();
// Move to first
Assert.IsTrue(_test.MoveNext());
return _test.Current;
}
}
-- If no parameters need to be passed to a procedure, simply:
BEGIN
MY_PACKAGE_NAME.MY_PROCEDURE_NAME
END;
Okay, so it seems the answer is -- no, there is no built in tool.
After setting /proc/sys/kernel/yama/ptrace_scope
to 0
, it is possible to use the strace
program. Further switches can be used to make it silent, so that it really waits passively:
strace -qqe '' -p <PID>
Spring cron expression for every day 1:01:am
@Scheduled(cron = "0 1 1 ? * *")
for more information check this information:
https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm
In View use this:
form.field.errors|striptags
for getting validation messages without html
def solve(s):
names = list(s.split(" "))
return " ".join([i.capitalize() for i in names])
Takes a input like your name: john doe
Returns the first letter capitalized.(if first character is a number, then no capitalization occurs)
works for any name length
dependencies: compile 'com.android.support:cardview-v7:23.1.1'
<android.support.v7.widget.CardView
android:layout_width="80dp"
android:layout_height="80dp"
android:elevation="12dp"
android:id="@+id/view2"
app:cardCornerRadius="40dp"
android:layout_centerHorizontal="true"
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="1.9">
<ImageView
android:layout_height="80dp"
android:layout_width="match_parent"
android:id="@+id/imageView1"
android:src="@drawable/Your_image"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
</android.support.v7.widget.CardView>
var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();
Easy and simple
my working code to go back screen.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(getApplicationContext(), "Home Clicked",
Toast.LENGTH_LONG).show();
// go to previous activity
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
I also got the same error. Reason for that I was compiling the project using Maven. I had JAVA_HOME pointing to JDK7 and hence java 1.7 was being used for compilation and when running the project I was using JDK1.5. Changing the below entry in .classpath file or change in the eclipse as in the screenshot resolved the issue.
classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5
There are two types of WITH clauses:
Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).
;WITH mil AS (
SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
FROM master.sys.all_columns as c
CROSS JOIN master.sys.all_columns as c2
)
SELECT CASE WHEN n % 3 = 0 THEN
CASE WHEN n % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
WHEN n % 5 = 0 THEN 'Buzz'
ELSE CAST(n AS char(6))
END + CHAR(13)
FROM mil
Here is a select statement also using a WITH clause
SELECT * FROM orders WITH (NOLOCK) where order_id = 123
Sometimes it's better to use neither. For example, in a "dispatch" situation, Javascript lets you do things in a completely different way:
function dispatch(funCode) {
var map = {
'explode': function() {
prepExplosive();
if (flammable()) issueWarning();
doExplode();
},
'hibernate': function() {
if (status() == 'sleeping') return;
// ... I can't keep making this stuff up
},
// ...
};
var thisFun = map[funCode];
if (thisFun) thisFun();
}
Setting up multi-way branching by creating an object has a lot of advantages. You can add and remove functionality dynamically. You can create the dispatch table from data. You can examine it programmatically. You can build the handlers with other functions.
There's the added overhead of a function call to get to the equivalent of a "case", but the advantage (when there are lots of cases) of a hash lookup to find the function for a particular key.
Using the constructor
BigInteger(String val)
Translates the decimal String representation of a BigInteger into a BigInteger.
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
template <class T>
void transpose( const std::vector< std::vector<T> > & a,
std::vector< std::vector<T> > & b,
int width, int height)
{
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
b[j][i] = a[i][j];
}
}
}
Simple 2020 no-tricks method:
body {
display: flex;
flex-direction: column;
}
#footer {
margin-top: auto;
}
For my system the problem ended up being that I still had Mysql 5.6 installed and so the mysql_upgrade.exe from that installation was being called instead of the one for 5.7. Navigate to C:\Program Files\MySQL\MySQL Server 5.7\bin
and run .\mysql_upgrade.exe -u root
Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage
And you can convert the entire object to a string, filename.json is expected to be located in documents folder.
var text = File.ReadAllText("filename.json");
var json = JsonValue.Parse(text);
while (JsonValue.Null != null)
{
Console.WriteLine(json.ToString());
}
Console.ReadLine();
Ok I know this a bit of a hack but this is a way to use a variable in a simple query, not a script:
WITH
emplVar AS
(SELECT 1234 AS id FROM dual)
SELECT
*
FROM
employees,
emplVar
WHERE
EmployId=emplVar.id;
You get to run it everywhere.
I stop at three parameters as a general rule of thumb. Any more and it's time to pass an array of parameters or a configuration object instead, which also allows for future parameters to be added without changing the API.
You can use regular expressions for this purpose, but it's good to avoid extra exceptions when input string mismatches against regular expression.
First to avoid extra headache of escaping to regex pattern - we could just use function for that purpose:
String reStrEnding = Regex.Escape("-");
I know that this does not do anything - as "-" is the same as Regex.Escape("=") == "="
, but it will make difference for example if character is @"\"
.
Then we need to match from begging of the string to string ending, or alternately if ending is not found - then match nothing. (Empty string)
Regex re = new Regex("^(.*?)" + reStrEnding);
If your application is performance critical - then separate line for new Regex, if not - you can have everything in one line.
And finally match against string and extract matched pattern:
String matched = re.Match(str).Groups[1].ToString();
And after that you can either write separate function, like it was done in another answer, or write inline lambda function. I've wrote now using both notations - inline lambda function (does not allow default parameter) or separate function call.
using System;
using System.Text.RegularExpressions;
static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
return new Regex("^(.*?)" + Regex.Escape(stopAt)).Match(text).Groups[1].Value;
}
}
class Program
{
static void Main(string[] args)
{
Regex re = new Regex("^(.*?)-");
Func<String, String> untilSlash = (s) => { return re.Match(s).Groups[1].ToString(); };
Console.WriteLine(untilSlash("223232-1.jpg"));
Console.WriteLine(untilSlash("443-2.jpg"));
Console.WriteLine(untilSlash("34443553-5.jpg"));
Console.WriteLine(untilSlash("noEnding(will result in empty string)"));
Console.WriteLine(untilSlash(""));
// Throws exception: Console.WriteLine(untilSlash(null));
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
}
}
Btw - changing regex pattern to "^(.*?)(-|$)"
will allow to pick up either until "-"
pattern or if pattern was not found - pick up everything until end of string.
You can pass in a pointer to a time_t
object that time
will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL
, it just ignores it and merely returns a new time_t
object that represents the current time.
From http://www.coderanch.com/t/236675/java-programmer-SCJP/certification/xff
The hex literal 0xFF is an equal int(255). Java represents int as 32 bits. It look like this in binary:
00000000 00000000 00000000 11111111
When you do a bit wise AND with this value(255) on any number, it is going to mask(make ZEROs) all but the lowest 8 bits of the number (will be as-is).
... 01100100 00000101 & ...00000000 11111111 = 00000000 00000101
& is something like % but not really.
And why 0xff? this in ((power of 2) - 1). All ((power of 2) - 1) (e.g 7, 255...) will behave something like % operator.
Then
In binary, 0 is, all zeros, and 255 looks like this:
00000000 00000000 00000000 11111111
And -1 looks like this
11111111 11111111 11111111 11111111
When you do a bitwise AND of 0xFF and any value from 0 to 255, the result is the exact same as the value. And if any value higher than 255 still the result will be within 0-255.
However, if you do:
-1 & 0xFF
you get
00000000 00000000 00000000 11111111
, which does NOT equal the original value of -1 (11111111
is 255 in decimal).
Few more bit manipulation: (Not related to the question)
X >> 1 = X/2
X << 1 = 2X
Check any particular bit is set(1) or not (0) then
int thirdBitTobeChecked = 1 << 2 (...0000100)
int onWhichThisHasTobeTested = 5 (.......101)
int isBitSet = onWhichThisHasTobeTested & thirdBitTobeChecked;
if(isBitSet > 0) {
//Third Bit is set to 1
}
Set(1) a particular bit
int thirdBitTobeSet = 1 << 2 (...0000100)
int onWhichThisHasTobeSet = 2 (.......010)
onWhichThisHasTobeSet |= thirdBitTobeSet;
ReSet(0) a particular bit
int thirdBitTobeReSet = ~(1 << 2) ; //(...1111011)
int onWhichThisHasTobeReSet = 6 ;//(.....000110)
onWhichThisHasTobeReSet &= thirdBitTobeReSet;
XOR
Just note that if you perform XOR operation twice, will results the same value.
byte toBeEncrypted = 0010 0110
byte salt = 0100 1011
byte encryptedVal = toBeEncrypted ^ salt == 0110 1101
byte decryptedVal = encryptedVal ^ salt == 0010 0110 == toBeEncrypted :)
One more logic with XOR is
if A (XOR) B == C (salt)
then C (XOR) B == A
C (XOR) A == B
The above is useful to swap two variables without temp like below
a = a ^ b; b = a ^ b; a = a ^ b;
OR
a ^= b ^= a ^= b;
finish() method is used to finish the activity and remove it from back stack. You can call it in any method in activity. But make sure you close all the Database connections, all reference variables null to prevent any memory leaks.
Stephen Taub has implemented a solution to this question, see Building Async Coordination Primitives, Part 7: AsyncReaderWriterLock.
Stephen Taub is highly regarded in the industry, so anything he writes is likely to be solid.
I won't reproduce the code that he posted on his blog, but I will show you how to use it:
/// <summary>
/// Demo class for reader/writer lock that supports async/await.
/// For source, see Stephen Taub's brilliant article, "Building Async Coordination
/// Primitives, Part 7: AsyncReaderWriterLock".
/// </summary>
public class AsyncReaderWriterLockDemo
{
private readonly IAsyncReaderWriterLock _lock = new AsyncReaderWriterLock();
public async void DemoCode()
{
using(var releaser = await _lock.ReaderLockAsync())
{
// Insert reads here.
// Multiple readers can access the lock simultaneously.
}
using (var releaser = await _lock.WriterLockAsync())
{
// Insert writes here.
// If a writer is in progress, then readers are blocked.
}
}
}
If you want a method that's baked into the .NET framework, use SemaphoreSlim.WaitAsync
instead. You won't get a reader/writer lock, but you will get tried and tested implementation.
In practical terms, Alnitak is correct and makes it easy to understand, but ultimately in JavaScript, everything is passed by value.
What is the "value" of an object? It is the object reference.
When you pass in an object, you get a copy of this value (hence the 'copy of a reference' that Alnitak described). If you change this value, you do not change the original object; you are changing your copy of that reference.
You must check this: Docblock Comment standards
I assume it is something in the lines of:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ChromeConsoleLogging {
private WebDriver driver;
@BeforeMethod
public void setUp() {
System.setProperty("webdriver.chrome.driver", "c:\\path\\to\\chromedriver.exe");
DesiredCapabilities caps = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(caps);
}
@AfterMethod
public void tearDown() {
driver.quit();
}
public void analyzeLog() {
LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
for (LogEntry entry : logEntries) {
System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
//do something useful with the data
}
}
@Test
public void testMethod() {
driver.get("http://mypage.com");
//do something on page
analyzeLog();
}
}
Source : Get chrome's console log
Of course it would be more simple if you extend jQuery like this:
$.fn.addClassDelay = function(className,delay) {
var $addClassDelayElement = $(this), $addClassName = className;
$addClassDelayElement.addClass($addClassName);
setTimeout(function(){
$addClassDelayElement.removeClass($addClassName);
},delay);
};
after that you can use this function like addClass:
$('div').addClassDelay('clicked',1000);
For a correct implementation, you need to change a series of things.
Database (immediately after the connection):
mysql_query("SET NAMES utf8");
// Meta tag HTML (probably it's already set):
meta charset="utf-8"
header php (before any output of the HTML):
header('Content-Type: text/html; charset=utf-8')
table-rows-charset (for each row):
utf8_unicode_ci
$animals = array('--Select Animal--', 'Cat', 'Dog', 'Cow');
$selected_key = $_POST['animal'];
$selected_val = $animals[$_POST['animal']];
Use your $animals list to generate your dropdown list; you now can get the key & the value of that key.
This question is old, the other answers are old. "Employed Russian"s answer is very good and informative, but it only works if you have the source code. If you don't, the alternatives back then were very tricky. Fortunately nowadays we have a simple solution to this problem (as commented in one of his replies), using patchelf. All you have to do is:
$ ./patchelf --set-interpreter /path/to/newglibc/ld-linux.so.2 --set-rpath /path/to/newglibc/ myapp
And after that, you can just execute your file:
$ ./myapp
No need to chroot
or manually edit binaries, thankfully. But remember to backup your binary before patching it, if you're not sure what you're doing, because it modifies your binary file. After you patch it, you can't restore the old path to interpreter/rpath. If it doesn't work, you'll have to keep patching it until you find the path that will actually work... Well, it doesn't have to be a trial-and-error process. For example, in OP's example, he needed GLIBC_2.3
, so you can easily find which lib provides that version using strings
:
$ strings /lib/i686/libc.so.6 | grep GLIBC_2.3
$ strings /path/to/newglib/libc.so.6 | grep GLIBC_2.3
In theory, the first grep would come empty because the system libc doesn't have the version he wants, and the 2nd one should output GLIBC_2.3 because it has the version myapp
is using, so we know we can patchelf
our binary using that path. If you get a segmentation fault, read the note at the end.
When you try to run a binary in linux, the binary tries to load the linker, then the libraries, and they should all be in the path and/or in the right place. If your problem is with the linker and you want to find out which path your binary is looking for, you can find out with this command:
$ readelf -l myapp | grep interpreter
[Requesting program interpreter: /lib/ld-linux.so.2]
If your problem is with the libs, commands that will give you the libs being used are:
$ readelf -d myapp | grep Shared
$ ldd myapp
This will list the libs that your binary needs, but you probably already know the problematic ones, since they are already yielding errors as in OP's case.
"patchelf" works for many different problems that you may encounter while trying to run a program, related to these 2 problems. For example, if you get: ELF file OS ABI invalid
, it may be fixed by setting a new loader (the --set-interpreter
part of the command) as I explain here. Another example is for the problem of getting No such file or directory
when you run a file that is there and executable, as exemplified here. In that particular case, OP was missing a link to the loader, but maybe in your case you don't have root access and can't create the link. Setting a new interpreter would solve your problem.
Thanks Employed Russian and Michael Pankov for the insight and solution!
Note for segmentation fault: you might be in the case where myapp
uses several libs, and most of them are ok but some are not; then you patchelf
it to a new dir, and you get segmentation fault. When you patchelf
your binary, you change the path of several libs, even if some were originally in a different path. Take a look at my example below:
$ ldd myapp
./myapp: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by ./myapp)
./myapp: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./myapp)
linux-vdso.so.1 => (0x00007fffb167c000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f9a9aad2000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f9a9a8ce000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f9a9a6af000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f9a9a3ab000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9a99fe6000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9a9adeb000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f9a99dcf000)
Note that most libs are in /lib/x86_64-linux-gnu/
but the problematic one (libstdc++.so.6
) is on /usr/lib/x86_64-linux-gnu
. After I patchelf'ed myapp
to point to /path/to/mylibs
, I got segmentation fault. For some reason, the libs are not totally compatible with the binary. Since myapp
didn't complain about the original libs, I copied them from /lib/x86_64-linux-gnu/
to /path/to/mylibs2
, and I also copied libstdc++.so.6
from /path/to/mylibs
there. Then I patchelf'ed it to /path/to/mylibs2
, and myapp
works now. If your binary uses different libs, and you have different versions, it might happen that you can't fix your situation. :( But if it's possible, mixing libs might be the way. It's not ideal, but maybe it will work. Good luck!
A VirtualHost would also work for this and may work better for you as you can host several projects without the need for subdirectories. Here's how you do it:
httpd.conf (or extra\httpd-vhosts.conf relative to httpd.conf. Trailing slashes "\" might cause it not to work):
NameVirtualHost *:80
# ...
<VirtualHost *:80>
DocumentRoot C:\projects\transitCalculator\trunk\
ServerName transitcalculator.localhost
<Directory C:\projects\transitCalculator\trunk\>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
HOSTS file (c:\windows\system32\drivers\etc\hosts usually):
# localhost entries
127.0.0.1 localhost transitcalculator.localhost
Now restart XAMPP and you should be able to access http://transitcalculator.localhost/ and it will map straight to that directory.
This can be helpful if you're trying to replicate a production environment where you're developing a site that will sit on the root of a domain name. You can, for example, point to files with absolute paths that will carry over to the server:
<img src="/images/logo.png" alt="My Logo" />
whereas in an environment using aliases or subdirectories, you'd need keep track of exactly where the "images" directory was relative to the current file.
Try to call randomize() before rand() to initialize random generator.
(look at: srand() — why call it only once?)
What happens if I promote the column to be a/the PK, too (a.k.a. identifying relationship)? As the column is now the PK, I must tag it with @Id (...).
This enhanced support of derived identifiers is actually part of the new stuff in JPA 2.0 (see the section 2.4.1 Primary Keys Corresponding to Derived Identities in the JPA 2.0 specification), JPA 1.0 doesn't allow Id
on a OneToOne
or ManyToOne
. With JPA 1.0, you'd have to use PrimaryKeyJoinColumn
and also define a Basic
Id
mapping for the foreign key column.
Now the question is: are @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?
You can obtain a similar result but using an Id
on OneToOne
or ManyToOne
is much simpler and is the preferred way to map derived identifiers with JPA 2.0. PrimaryKeyJoinColumn
might still be used in a JOINED inheritance strategy. Below the relevant section from the JPA 2.0 specification:
11.1.40 PrimaryKeyJoinColumn Annotation
The
PrimaryKeyJoinColumn
annotation specifies a primary key column that is used as a foreign key to join to another table.The
PrimaryKeyJoinColumn
annotation is used to join the primary table of an entity subclass in theJOINED
mapping strategy to the primary table of its superclass; it is used within aSecondaryTable
annotation to join a secondary table to a primary table; and it may be used in aOneToOne
mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity[108]....
If no
PrimaryKeyJoinColumn
annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass....
Example: Customer and ValuedCustomer subclass
@Entity @Table(name="CUST") @Inheritance(strategy=JOINED) @DiscriminatorValue("CUST") public class Customer { ... } @Entity @Table(name="VCUST") @DiscriminatorValue("VCUST") @PrimaryKeyJoinColumn(name="CUST_ID") public class ValuedCustomer extends Customer { ... }
[108] The derived id mechanisms described in section 2.4.1.1 are now to be preferred over
PrimaryKeyJoinColumn
for the OneToOne mapping case.
This source http://weblogs.java.net/blog/felipegaucho/archive/2009/10/24/jpa-join-table-additional-state states that using @ManyToOne and @Id works with JPA 1.x. Who's correct now?
The author is using a pre release JPA 2.0 compliant version of EclipseLink (version 2.0.0-M7 at the time of the article) to write an article about JPA 1.0(!). This article is misleading, the author is using something that is NOT part of JPA 1.0.
For the record, support of Id
on OneToOne
and ManyToOne
has been added in EclipseLink 1.1 (see this message from James Sutherland, EclipseLink comitter and main contributor of the Java Persistence wiki book). But let me insist, this is NOT part of JPA 1.0.
It's as easy as:
delete object.keyname;
or
delete object["keyname"];
Hey you can use this class to get Screen Width and Height in percentage
import 'package:flutter/material.dart';
class Responsive{
static width(double p,BuildContext context)
{
return MediaQuery.of(context).size.width*(p/100);
}
static height(double p,BuildContext context)
{
return MediaQuery.of(context).size.height*(p/100);
}
}
and to Use like this
Container(height: Responsive.width(100, context), width: Responsive.width(50, context),);
M-^ is copy Text. "M" in my environment is "Esc" key ! not "Ctrl"; so I use Esc + 6 to copy that.
[nano help] Escape-key sequences are notated with the Meta (M-) symbol and can be entered using either the Esc, Alt, or Meta key depending on your keyboard setup.
As name itself suggest it reflects what it holds for example class method,etc apart from providing feature to invoke method creating instance dynamically at runtime.
It is used by many frameworks and application under the wood to invoke services without actually knowing the code.
For the ones starting a rails app with existing database there is a cool gem called schema_to_scaffold
to generate a scaffold script.
it outputs:
rails g scaffold users fname:string lname:string bdate:date email:string encrypted_password:string
from your schema.rb
our your renamed schema.rb.
Check it
Actually you can do this.
$state.go("state-name", {param-name: param-value}, {location: false, inherit: false});
This is the official documentation about options in state.go
Everything is described there and as you can see this is the way to be done.
This code works to insert both header and footer on the first page with header center aligned and footer left aligned
\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
% for the first page
\def\ps@IEEEtitlepagestyle{%
\old@ps@IEEEtitlepagestyle%
\def\@oddhead{\strut\hfill#1\hfill\strut}%
\def\@evenhead{\strut\hfill#1\hfill\strut}%
\def\@oddfoot{\mycopyrightnotice}
\def\@evenfoot{}
}%
\ps@headings%
}
\makeatother
\confheader{%
5$^{th}$ IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}
\def\mycopyrightnotice{
{\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
\gdef\mycopyrightnotice{}
}
\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```
I never had any luck with that approach. I always do this (hope this helps):
var obj = {};
obj.first_name = $("#namec").val();
obj.last_name = $("#surnamec").val();
obj.email = $("#emailc").val();
obj.mobile = $("#numberc").val();
obj.password = $("#passwordc").val();
Then in your ajax:
$.ajax({
type: "POST",
url: hb_base_url + "consumer",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(obj),
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
You can find so many different sorting algorithms in internet, but if you want to fix your own solution you can do following changes in your code:
Instead of:
orderedNums[greater]=tenNums[indexL];
you need to do this:
while (orderedNums[greater] == tenNums[indexL]) {
greater++;
}
orderedNums[greater] = tenNums[indexL];
This code basically checks if that particular index is occupied by a similar number, then it will try to find next free index.
Note: Since the default value in your sorted array elements is 0, you need to make sure 0 is not in your list. otherwise you need
to initiate your sorted array with an especial number that you sure is
not in your list e.g: Integer.MAX_VALUE
I found the following code easy and working. Original answer is here https://www.postgresql.org/message-id/[email protected]
prova=> create table test(t text, i integer);
CREATE
prova=> insert into test values('123',123);
INSERT 64579 1
prova=> select cast(i as text),cast(t as int)from test;
text|int4
----+----
123| 123
(1 row)
hope it helps
Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.
Update
Based on Manipulating the browser history, passing the empty string as second parameter of pushState
method (aka title) should be safe against future changes to the method, so it's better to use pushState
like this:
history.pushState(null, '', '/en/step2');
You can read more about that in mentioned article
Original Answer
Use history.pushState
like this:
history.pushState(null, null, '/en/step2');
Update 2 to answer Idan Dagan's comment:
Why not using
history.replaceState()
?
From MDN
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one
That means if you use replaceState
, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.
Update 3 to add window.onpopstate
So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState
, you can detect the back/forward button navigation by using window.onpopstate
like this:
window.onpopstate = function(e) {
// ...
};
As the first argument of pushState
is an object, if you passed an object
instead of null
, you can access that object in onpopstate
which is very handy, here is how:
window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
Update 4 to add Reading the current state:
When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate
event using the history.state
property like this:
console.log(history.state);
Bonus: Use following to check history.pushState
support:
if (history.pushState) {
// \o/
}
I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.
The installation is pretty simple:
Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.
Then, I created a file, in my project root, called environment.env
which contains:
DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1
Then I went to Run->Edit Configurations, and I followed the steps in the next image:
In 3, I chose the file environment.env
, and then I could just click the play button in PyCharm, and everything worked like a charm.
The usual way
The usual way to create what you're asking for, is to simply do the following:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "The status update text");
startActivity(Intent.createChooser(intent, "Dialog title text"));
This works without any issues for me.
The alternative way (maybe)
The potential problem with doing this, is that you're also allowing the message to be sent via e-mail, SMS, etc. The following code is something I'm using in an application, that allows the user to send me an e-mail using Gmail. I'm guessing you could try to change it to make it work with Facebook only.
I'm not sure how it responds to any errors or exceptions (I'm guessing that would occur if Facebook is not installed), so you might have to test it a bit.
try {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
String[] recipients = new String[]{"e-mail address"};
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "E-mail subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "E-mail text");
emailIntent.setType("plain/text"); // This is incorrect MIME, but Gmail is one of the only apps that responds to it - this might need to be replaced with text/plain for Facebook
final PackageManager pm = getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") ||
info.activityInfo.name.toLowerCase().contains("gmail")) best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
startActivity(emailIntent);
} catch (Exception e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
Usually it would be this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>='2010-10-01'
AND yourtimetimefield< '2010-11-01'
But because you have a unix timestamps, you'll need something like this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>=unix_timestamp('2010-10-01')
AND yourtimetimefield< unix_timestamp('2010-11-01')
A Kotlin extension + some padding around the drawable
fun TextView.addDrawable(drawable: Int) {
val imgDrawable = ContextCompat.getDrawable(context, drawable)
compoundDrawablePadding = 32
setCompoundDrawablesWithIntrinsicBounds(imgDrawable, null, null, null)
}
You could also use the apache library and do this:
StringUtils.split(test, "|");
Support Python2&3 using hook (from https://stackoverflow.com/a/33571117/558397)
import requests
import six
from six import iteritems
requests.packages.urllib3.disable_warnings() # @UndefinedVariable
r = requests.get("http://echo.jsontest.com/key/value/one/two/three", verify=False)
def _byteify(data):
# if this is a unicode string, return its string representation
if isinstance(data, six.string_types):
return str(data.encode('utf-8').decode())
# if this is a list of values, return list of byteified values
if isinstance(data, list):
return [ _byteify(item) for item in data ]
# if this is a dictionary, return dictionary of byteified keys and values
# but only if we haven't already byteified it
if isinstance(data, dict):
return {
_byteify(key): _byteify(value) for key, value in iteritems(data)
}
# if it's anything else, return it in its original form
return data
w = r.json(object_hook=_byteify)
print(w)
Returns:
{'three': '', 'key': 'value', 'one': 'two'}
Use Application.GetSaveAsFilename()
in the same way that you used Application.GetOpenFilename()
Try this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
</androidx.constraintlayout.widget.ConstraintLayout>
/>
_x000D_
the main issue with the following error:
no drawer view found with absolute gravity LEFT
is that, you defined the
android:layout_gravity="right"
for list-view in right, but try to open the drawer from left, by calling this function:
mDrawerToggle.syncState();
and clicking on hamburger icon!
just comment the above function and try to handle open/close of menu like @Rudi said!
See this answer: there is in Ruby 1.9.2, but not in earlier versions. Personally I think rand(8) + 3 is fine, but if you're interested check out the Random class described in the link.
I had the same problem that is really easy to make, but took me a while to see through.
I had copied the declaration to where I was using it and had left the 'self' argument there, but it took me ages to realise that.
I had
self.myFunction(self, a, b, c='123')
but it should have been
self.myFunction(a, b, c='123')
Thank you for all answers! I found it! It calls "Column selection (for Sublime)" and "Column Mode Editing (for Notepad++)" https://www.sublimetext.com/docs/3/column_selection.html
A smaller version (when compared to previous ones):
var customer = context.Find(id);
context.Delete(customer);
context.SaveChanges();
You can find what is the php.ini file used:
Next, you can find the information in the Loaded Configuration file (so here it's /user/local/etc/php/php.ini)
Sometimes, you have indicated (none), in this case you just have to put your custom php.ini that you can find here: http://git.php.net/?p=php-src.git;a=blob;f=php.ini-production;hb=HEAD
I hope this answer will help.
In WSDL, if you look at the Binding section, you will clearly see that soap binding is explicitly mentioned if the service uses soap 1.2. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="findEmployeeById">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation><operation name="create">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation>
</binding>
if the web service use soap 1.1, it will not explicitly define any soap version in the WSDL file under binding section. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
<operation name="findEmployeeById">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation><operation name="create">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation>
</binding>
How to determine the SOAP version of the SOAP message?
but remember that this is not much recommended way to determine the soap version that your web services uses. the version of the soap message can be determined using one of following ways.
1. checking the namespace of the soap message
SOAP 1.1 namespace : http://schemas.xmlsoap.org/soap/envelope
SOAP 1.2 namespace : http://www.w3.org/2003/05/soap-envelope
2. checking the transport binding information (http header information) of the soap message
SOAP 1.1 : user text/xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: text/xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
SOAP 1.2 : user application/soap+xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: application/soap+xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
3. using SOAP fault information
The structure of a SOAP fault message between the two versions are different.
We just released pako https://github.com/nodeca/pako , port of zlib to javascript. I think that's now the fastest js implementation of deflate / inflate / gzip / ungzip. Also, it has democratic MIT licence. Pako supports all zlib options and it's results are binary equal.
Example:
var inflate = require('pako/lib/inflate').inflate;
var text = inflate(zipped, {to: 'string'});
This is helpful for testing purposes.
Seq.empty[String].toDF()
This was added in a comment by @jackocnr but I missed it. For modern browsers I think this is the best approach.
It makes the inner element fill the whole container if it's too small, but expands the container's height if it's too big.
#containment {
min-height: 100%;
display: flex;
flex-direction: column;
}
#containment-shadow-left {
flex: 1;
}
check out this.
<activity android:name=".Calculator"
android:windowSoftInputMode="stateHidden|adjustResize"
android:theme="@android:style/Theme.Black.NoTitleBar">
</activity>
<input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57" ondragstart="return false;" ondrop="return false;">
Input filed only accept numbers, But it's temporary fix only.
I use an immediately invoked lambda for these scenarios:
const config = (() => {
try {
return JSON.parse(fs.readFileSync('config.json'));
} catch (error) {
return {};
}
})();
async
version:
const config = await (async () => {
try {
return JSON.parse(await fs.readFileAsync('config.json'));
} catch (error) {
return {};
}
})();
As pointed out (and hopefully unsurprisingly), using if+else
is indeed the idiomatic way to do conditionals in Go.
In addition to the full blown var+if+else
block of code, though, this spelling is also used often:
index := val
if val <= 0 {
index = -val
}
and if you have a block of code that is repetitive enough, such as the equivalent of int value = a <= b ? a : b
, you can create a function to hold it:
func min(a, b int) int {
if a <= b {
return a
}
return b
}
...
value := min(a, b)
The compiler will inline such simple functions, so it's fast, more clear, and shorter.
How to set a textbox format as 8 digit number(00000019)
string i = TextBox1.Text;
string Key = i.ToString().PadLeft(8, '0');
Response.Write(Key);
No. Pylint doesn't currently let you discriminate between doc-string warnings.
However, you can use Flake8 for all Python code checking along with the doc-string extension to ignore this warning.
Install the doc-string extension with pip (internally, it uses pydocstyle).
pip install flake8_docstrings
You can then just use the --ignore D100
switch. For example, flake8 file.py --ignore D100
With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
var c = "\001",
sel = document.selection.createRange(),
dul = sel.duplicate(),
len = 0;
dul.moveToElementText(node);
sel.text = c;
len = dul.text.indexOf(c);
sel.moveStart('character',-1);
sel.text = "";
return len;
}
I also recommend you to check the jQuery FieldSelection Plugin, it allows you to do that and much more...
Edit: I actually re-implemented the above code:
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
Check an example here.
string test = "<body><head>test header</head></body>";
XmlDocument xmltest = new XmlDocument();
xmltest.LoadXml(test);
XmlNodeList elemlist = xmltest.GetElementsByTagName("head");
string result = elemlist[0].InnerXml;
//result -> "test header"
'''
w write mode
r read mode
a append mode
w+ create file if it doesn't exist and open it in (over)write mode
[it overwrites the file if it already exists]
r+ open an existing file in read+write mode
a+ create file if it doesn't exist and open it in append mode
'''
example:
file_name = 'my_file.txt'
f = open(file_name, 'a+') # open file in append mode
f.write('python rules')
f.close()
I hope this helps. [FYI am using python version 3.6.2]
I think :hover
was missing in above answers. So following would do the needful.(if css was required)
#myDiv:hover
{
cursor: pointer;
}
Sorry for dredging up an old post, but it has a lot of views. I faced a similar problem this week and came up with this pattern:
declare @example table ( sampletext varchar( 50 ) );
insert @example values
( 'The quick brown fox jumped over the lazy dog.' ),
( 'Ask not what your country can do for you.' ),
( 'Cupcakes are the new hotness.' );
declare @filter table ( searchtext varchar( 50 ) );
insert @filter values
( 'lazy' ),
( 'hotness' ),
( 'cupcakes' );
-- Expect to get rows 1 and 3, but no duplication from Cupcakes and Hotness
select *
from @example e
where exists ( select * from @filter f where e.sampletext like '%' + searchtext + '%' )
Exists() works a little better than join, IMO, because it just tests each record in the set, but doesn't cause duplication if there are multiple matches.
this also works:
a=pd.DataFrame({'A':a.groupby('A')['B'].max().index,'B':a.groupby('A') ['B'].max().values})
fastest way is to use the .is()
jQuery function.
if ( $('input').is('[readonly]') ) { }
using [readonly]
as a selector simply checks if the attribute is defined on your element. if you want to check for a value, you can use something like this instead:
if ( $('input').is('[readonly="somevalue"]') ) { }
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
},1000);
You shouldn't have to unserialize anything in PHP from the jquery serialize
method. If you serialize the data, it should be sent to PHP as query parameters if you are using a GET method ajax request or post vars if you are using a POST ajax request. So in PHP, you would access values like $_POST["varname"]
or $_GET["varname"]
depending on the request type.
The serialize
method just takes the form elements and puts them in string form. "varname=val&var2=val2"
Just use has_one
instead of belongs_to
in your :through
, like this:
class Choice
belongs_to :user
belongs_to :answer
has_one :question, :through => :answer
end
Unrelated, but I'd be hesitant to use validates_uniqueness_of instead of using a proper unique constraint in your database. When you do this in ruby you have race conditions.
You can use
If-then-else: (if) ? (then) : (else)
Example:
'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
It could be useful for the new people asking the same question.
777
!If you use nginx (like me), just change the ownership of the folders under /var/lib/php/
from apache
to nginx
:
[root@centos ~]# cd /var/lib/php/
[root@centos php]# ll
total 12
drwxrwx---. 2 root apache 4096 Jan 30 16:23 opcache
drwxrwx---. 2 root apache 4096 Feb 5 20:56 session
drwxrwx---. 2 root apache 4096 Jan 30 16:23 wsdlcache
[root@centos php]# chown -R :nginx opcache/
[root@centos php]# chown -R :nginx session/
[root@centos php]# chown -R :nginx wsdlcache/
[root@centos php]# ll
total 12
drwxrwx---. 2 root nginx 4096 Jan 30 16:23 opcache
drwxrwx---. 2 root nginx 4096 Feb 5 20:56 session
drwxrwx---. 2 root nginx 4096 Jan 30 16:23 wsdlcache
And also for the folders under /var/lib/phpMyAdmin/
:
[root@centos php]# cd /var/lib/phpMyAdmin
[root@centos phpMyAdmin]# ll
total 12
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 config
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 save
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 upload
[root@centos phpMyAdmin]# chown -R nginx:nginx config/
[root@centos phpMyAdmin]# chown -R nginx:nginx save/
[root@centos phpMyAdmin]# chown -R nginx:nginx upload/
[root@centos phpMyAdmin]# ll
total 12
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 config
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 save
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 upload
I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.
Here's the pypi https://pypi.python.org/pypi/cx_Freeze
The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html
I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.
The same error message results not only for null
but also for e.g. factor(0)
. In this case, the query must be if(length(element) > 0 & otherCondition)
or better check both cases with if(!is.null(element) & length(element) > 0 & otherCondition)
.
It's cultural. In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you really want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers to be responsible. In practice, this works very nicely.
If you want to emulate private variables for some reason, you can always use the __
prefix from PEP 8. Python mangles the names of variables like __foo
so that they're not easily visible to code outside the class that contains them (although you can get around it if you're determined enough, just like you can get around Java's protections if you work at it).
By the same convention, the _
prefix means stay away even if you're not technically prevented from doing so. You don't play around with another class's variables that look like __foo
or _bar
.
The method .appendChild()
is used to add a new element NOT add text to an existing element.
Example:
var p = document.createElement("p");
document.body.appendChild(p);
Reference: Mozilla Developer Network
The standard approach for this is using .innerHTML()
. But if you want a alternate solution you could try using element.textContent
.
Example:
document.getElementById("foo").textContent = "This is som text";
Reference: Mozilla Developer Network
How ever this is only supported in IE 9+
Old question but just had that problem /dumb jira having problems with java 10/ and didn't find a simple answer here so just gonna leave it:
$ /usr/libexec/java_home -V
shows the versions installed and their locations so you can simply remove /Library/Java/JavaVirtualMachines/<the_version_you_want_to_remove>
. Voila
You can use jQuery change() function
$('input').change(function(){
//your codes
});
There are examples on how to use it on the API Page: http://api.jquery.com/change/
# Original code
df = pd.DataFrame({'a': [1, 2, 3, 'bad', 5],
'b': [0.1, 0.2, 0.3, 0.4, 0.5],
'item': ['a', 'b', 'c', 'd', 'e']})
df = df.set_index('item')
Convert to numeric using 'coerce' which fills bad values with 'nan'
a = pd.to_numeric(df.a, errors='coerce')
Use isna to return a boolean index:
idx = a.isna()
Apply that index to the data frame:
df[idx]
Returns the row with the bad data in it:
a b
item
d bad 0.4
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);
/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);
This means the npm command is getting an HTML document instead of whatever format it is looking for. In my case, I was using sinopia. When I no longer wanted to use it, I accidentally used this command to reset the registry:
npm config set registry https://www.npmjs.com/
which was wrong, and it should have been the command already mentioned here. Read this if none of the answers solve this problem, and you can probably figure out where the incorrect URL is present and clear it off, and set the registry to the correct URL:
npm config set registry https://registry.npmjs.org
If you know the settings in advance you can define it in a single statement:
var defaultsettings = {
ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. },
uisettings : { "ui1" : "v1", "ui22" : "v2", etc }
};
If you don't know the values in advance you can just define the top level object and then add properties:
var defaultsettings = { };
defaultsettings["ajaxsettings"] = {};
defaultsettings["ajaxsettings"]["somekey"] = "some value";
Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects:
var defaultsettings = {
ajaxsettings : { },
uisettings : { }
};
defaultsettings["ajaxsettings"]["somekey"] = "some value";
defaultsettings["uisettings"]["somekey"] = "some value";
You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable:
var keyname = "ajaxsettings";
var defaultsettings = {};
defaultsettings[keyname] = {};
defaultsettings[keyname]["some key"] = "some value";
Note that you can not use variables for key names in the { } literal syntax.
I have another case when I have no chance to put CDATA into the xml as I receive the string HTML from a server.
Here is what I get from a server:
<p>The quick brown <br />
fox jumps <br />
over the lazy dog<br />
</p>
It seems to be more complicated but the solution is much simpler.
private TextView textView;
protected void onCreate(Bundle savedInstanceState) {
.....
textView = (TextView) findViewById(R.id.text); //need to define in your layout
String htmlFromServer = getHTMLContentFromAServer();
textView.setText(Html.fromHtml(htmlFromServer).toString());
}
Hope it helps!
Linh
Change database charset and collation
ALTER DATABASE
database_name
CHARACTER SET = utf8mb4
COLLATE = utf8mb4_unicode_ci;
change specific table's charset and collation
ALTER TABLE
table_name
CONVERT TO CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
change connection charset in mysql driver
before
charset=utf8&parseTime=True&loc=Local
after
charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=True&loc=Local
From this article https://hackernoon.com/today-i-learned-storing-emoji-to-mysql-with-golang-204a093454b7
If you want to directly get the package name of the current app in focus, use this adb command -
adb shell dumpsys window windows | grep -E 'mFocusedApp'| cut -d / -f 1 | cut -d " " -f 7
Extra info from the result of the adb command is removed using the cut command. Original solution from here.
There is no such tool till now to print the heap memory in the format as you requested The Only and only way to print is to write a java program with the help of Runtime Class,
public class TestMemory {
public static void main(String [] args) {
int MB = 1024*1024;
//Getting the runtime reference from system
Runtime runtime = Runtime.getRuntime();
//Print used memory
System.out.println("Used Memory:"
+ (runtime.totalMemory() - runtime.freeMemory()) / MB);
//Print free memory
System.out.println("Free Memory:"
+ runtime.freeMemory() / mb);
//Print total available memory
System.out.println("Total Memory:" + runtime.totalMemory() / MB);
//Print Maximum available memory
System.out.println("Max Memory:" + runtime.maxMemory() / MB);
}
}
reference:https://viralpatel.net/blogs/getting-jvm-heap-size-used-memory-total-memory-using-java-runtime/
You can also use
cd %localhost%
to set the directory to the folder the batch file was opened from. Your script would look like this:
@echo off
cd %localhost%
echo .> dblank.txt
Make sure you set the directory before you use the command to create the text file.
I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20
The support library android-support-v4.jar
is causing this conflict, just delete the library under /libs
folder of your project, don´t be scared, the library is already contained in the library appcompat_v7
, clean and build your project, and your project will work like a charm!
There has been some major changes in ms 2008 -> Might be worth considering the following article when making a decisions on what data type to use. http://msdn.microsoft.com/en-us/library/ms143432.aspx
Bytes per
Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.
The variable Random
is only "in scope" inside the main
method. It's not accessible to any methods called by main
. When you return from main
, the variable disappears (it's part of the stack frame).
If you want all of the methods of your class to use the same Random
instance, declare a member variable:
class MyObj {
private final Random random = new Random();
public void compTurn() {
while (true) {
int a = random.nextInt(10);
if (possibles[a] == 1)
break;
}
}
}
DataTable dataTable = new DataTable();
dataTable = OldDataTable.Tables[0].Clone();
foreach(DataRow dr in RowData.Tables[0].Rows)
{
DataRow AddNewRow = dataTable.AddNewRow();
AddNewRow.ItemArray = dr.ItemArray;
dataTable.Rows.Add(AddNewRow);
}
The answers by Brandon and fatbotdesigns are both correct, but having implemented the Google docs preview, we found multiple .docx files that couldn't be handled by Google. Switched to the MS Office Online preview and works likes a charm.
My recommendation would be to use the MS Office Preview URL over Google's.
https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc'
Your userPhotos
array is option-typed, you should retrieve the actual underlying object with !
(if you want an error in case the object isn't there) or ?
(if you want to receive nil
in url):
let userPhotos = currentUser?.photos
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
But to preserve safe nil handling, you better use functional approach, for instance, with map
, like this:
let urls = userPhotos?.map{ $0.url }
Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
Even if WHERE textcolumn LIKE "%SUBSTRING%"
is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).
If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")
In short:
In MySQL Workbench 6.0+
With this setting you will be able to concatenate fields without getting blobs.
I think this applies to versions 5.2.22 and later and is the result of this MySQL bug.
Disclaimer: I don't know what the downside of this setting is - maybe when you are selecting BINARY
/VARBINARY
values you will see it as plain text which may be misleading and/or maybe it will hinder performance if they are large enough?
When you say 2^8
you get 256
, but the numbers in computers terms begins from the number 0
. So, then you got the 255
, you can probe it in a internet mask for the IP or in the IP itself.
255
is the maximum value of a 8 bit integer : 11111111 = 255
Does that help?
In an attempt to find a way to make the target cell for the intersect method a name table array, I stumbled across a simple way to run something when ANY cell or set of cells on a particular sheet changes. This code is placed in the worksheet module as well:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Cells.Count > 0 Then
'mycode here
end if
end sub
Specify negative value to spread value. This works for me:
box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);
Its actually enough to add -m to startup parameters on Sql Server Configuration Manager, restart service, go to ssms an add checkbox sysadmin on your account, then remove -m restart again and use as usual.
Database Engine Service Startup Options
-m Starts an instance of SQL Server in single-user mode.
Your first problem is a limitation of the PRINT
statement. I'm not sure why sp_executesql
is failing. It should support pretty much any length of input.
Perhaps the reason the query is malformed is something other than truncation.
You can also use switch case like
String columndata2 = "";
if (cell.getColumnIndex() == 1) {// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
columndata2 = "";
break;
case Cell.CELL_TYPE_NUMERIC:
columndata2 = "" + cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING:
columndata2 = cell.getStringCellValue();
break;
}
}
System.out.println("Cell Value "+ columndata2);
As mentioned before, the use of x(end+1) = newElem
has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.
However, what should not be forgotten is that x = [x newElem]
will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]
All in all, if you want a solution that allows you to concatenate your existing vector x
with newElem
that may or may not be a scalar, this should do the trick:
x(end+(1:numel(newElem)))=newElem
Plugins -> Plugin Manager -> Show Plugin Manager -> Setting -> Check mark On Force HTTP instead of HTTPS for downloading Plugin List & Use development plugin list (may contain untested, unvalidated or un-installable plugins). -> OK.
You can also done this by using group by clause
SELECT purchases.address_id, purchases.* FROM "purchases"
WHERE "purchases"."product_id" = 1 GROUP BY address_id,
purchases.purchased_at ORDER purchases.purchased_at DESC
If you meant disable all the inputs in an Angular form at once:
1- Reactive Forms:
myFormGroup.disable() // where myFormGroup is a FormGroup
2- Template driven forms (NgForm):
You should get hold of the NgForm in a NgForm variable (for ex. named myNgForm) then
myNgForm.form.disable() // where form here is an attribute of NgForm
// & of type FormGroup so it accepts the disable() function
In case of NgForm , take care to call the disable method in the right time
To determine when to call it, You can find more details in this Stackoverflow answer
You can call ViewController this way, If you want with NavigationController
1.In current Screen : Load new screen
VerifyExpViewController *addProjectViewController = [[VerifyExpViewController alloc] init];
[self.navigationController pushViewController:addProjectViewController animated:YES];
2.1 In Loaded View : add below in .h file
@interface VerifyExpViewController : UIViewController <UINavigationControllerDelegate>
2.2 In Loaded View : add below in .m file
@implementation VerifyExpViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.delegate = self;
[self setNavigationBar];
}
-(void)setNavigationBar
{
self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
self.navigationController.navigationBar.translucent = YES;
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"B_topbar.png"] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
self.navigationItem.hidesBackButton = YES;
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Btn_topback.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onBackButtonTap:)];
self.navigationItem.leftBarButtonItem.tintColor = [UIColor lightGrayColor];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Save.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onSaveButtonTap:)];
self.navigationItem.rightBarButtonItem.tintColor = [UIColor lightGrayColor];
}
-(void)onBackButtonTap:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)onSaveButtonTap:(id)sender
{
//todo for save button
}
@end
Hope this will be useful for someone there :)
You can achieve it using appending
API. This returns a new string made by appending a given string to the receiver.
API Details : here
Use:
var text = "Hello"
text = text.appending(" Namaste")
Result:
Hello
Hello Namaste
Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:
Html.Hidden("Name", "Value")
Will result in:
<input id="Name" name="Name" type="hidden" value="Value">
In your controller, you might have an action like:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
}
And a model like:
public class MyModel
{
public string Name { get; set; }
}
The raw Html.Hidden
we used above will get correlated to the Name
property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name
property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor
, you get protected from that:
Html.HiddenFor(x => x.Name, "Value");
Now, if you rename the Name
property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x.
.
The problem still not resolved after remove the '.', then it start points the error to my folder. As i added this folder first time then i restarted the PyCharm and it automatically resolved the issue
Try this it may help you:
public void ButtonClick(View view) {
Fragment mFragment = new YourNextFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mFragment).commit();
}
From https://developer.mozilla.org/en-US/docs/Web/CSS/background-color
To set background color:
/* Hexadecimal value with color and 100% transparency*/
background-color: #11ffee00; /* Fully transparent */
/* Special keyword values */
background-color: transparent;
/* HSL value with color and 100% transparency*/
background-color: hsla(50, 33%, 25%, 1.00); /* 100% transparent */
/* RGB value with color and 100% transparency*/
background-color: rgba(117, 190, 218, 1.0); /* 100% transparent */
I put my .vm under the src/main/resources/templates
, then the code is :
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init( p );
VelocityContext context = new VelocityContext();
Template template = Velocity.getTemplate("templates/my.vm");
this works in web project.
In eclipse Velocity.getTemplate("my.vm") works since velocity will look for the .vm file in src/main/resources/ or src/main/resources/templates, but in web project, we have to use Velocity.getTemplate("templates/my.vm");
I also received this error, what I needed was to specify the database where the user authentication data was stored:
mongo -u admin -p SECRETPASSWORD --authenticationDatabase admin
Update Nov 18 2017:
mongo admin -u admin -p
is a better solution. Mongo will prompt you for your password, this way you won't put your cleartext password into the shell history which is just terrible security practice.
Updating to the latest version of Chrome (63.0.3239.84) via Help -> About fixed it for me.
(actually, I did had to switch to Offline and back to Online in the Network tab of developers tools to make the last errors go away.)
There is no semicolon at the end of that instruction causing the error.
EDIT
Like RiverC pointed out, there is no semicolon at the end of the previous line!
require ("scripts/connect.php")
EDIT
It seems you have no-semicolons whatsoever.
http://php.net/manual/en/language.basic-syntax.instruction-separation.php
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.
to check:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
document.getElementById("id-of-checkbox").checked = false;
If you decide to go for a minimal approach, without libpng/libjpeg dependencies, I suggest using stb_image
and stb_image_write
, found here.
It's as simple as it gets, you just need to place the header files stb_image.h
and stb_image_write.h
in your folder.
Here's the code that you need to read images:
#include <stdint.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
int main() {
int width, height, bpp;
uint8_t* rgb_image = stbi_load("image.png", &width, &height, &bpp, 3);
stbi_image_free(rgb_image);
return 0;
}
And here's the code to write an image:
#include <stdint.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#define CHANNEL_NUM 3
int main() {
int width = 800;
int height = 800;
uint8_t* rgb_image;
rgb_image = malloc(width*height*CHANNEL_NUM);
// Write your code to populate rgb_image here
stbi_write_png("image.png", width, height, CHANNEL_NUM, rgb_image, width*CHANNEL_NUM);
return 0;
}
You can compile without flags or dependencies:
g++ main.cpp
Other lightweight alternatives include:
I had the same problem for Winforms.
The solution for me is:
Install-Package Microsoft.ReportViewer.Runtime.Winforms
(//*[@attribute='value'])[index] to find target of element while your finding multiple matches in it
df = df.loc[:, ~df.columns.str.contains('^Unnamed')]
In [162]: df
Out[162]:
colA ColB colC colD colE colF colG
0 44 45 26 26 40 26 46
1 47 16 38 47 48 22 37
2 19 28 36 18 40 18 46
3 50 14 12 33 12 44 23
4 39 47 16 42 33 48 38
if the first column in the CSV file has index values, then you can do this instead:
df = pd.read_csv('data.csv', index_col=0)
Address already in use
means that the port
you are trying to allocate for your current execution is already occupied/allocated to some other process.
If you are a developer and if you are working on an application which require lots of testing, you might have an instance of your same application running in background (may be you forgot to stop it properly)
So if you encounter this error, just see which application/process is using the port.
In linux try using netstat -tulpn
. This command will list down a process list with all running processes.
Check if an application is using your port. If that application or process is another important one then you might want to use another port which is not used by any process/application.
Anyway you can stop the process which uses your port and let your application take it.
If you are in linux environment try,
netstat -tulpn
to display the processeskill <pid>
This will terminate the processIf you are using windows,
netstat -a -o -n
to check for the port usagestaskkill /F /PID <pid>
to kill that processI want to check tha in the following array $arr
is there 'abc' exists in sub arrays or not
$arr = array(
array(
'title' => 'abc'
)
);
Then i can use this
$res = array_search('abc', array_column($arr, 'title'));
if($res == ''){
echo 'exists';
} else {
echo 'notExists';
}
I think This is the Most simple way to define
First I am afraid your question contains a little mistake. There is not method writeline in class Console. Instead class Console provides method writer() that returns PrintWriter. This print writer has println().
Now what is the difference between
System.console().writer().println("hello from console");
and
System.out.println("hello system out");
If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.
Here is an example I have just implemented.
import java.io.Console;
public class TestConsole {
public static void main(String[] args) {
Console console = System.console();
System.out.println("console=" + console);
console.writer().println("hello from console");
}
}
When I ran the application from command prompt I got the following:
$ java TestConsole
console=java.io.Console@93dcd
hello from console
but when I redirected the STDOUT to file...
$ java TestConsole >/tmp/test
Exception in thread "main" java.lang.NullPointerException
at TestConsole.main(TestConsole.java:8)
Line 8 is console.writer().println()
.
Here is the content of /tmp/test
console=null
I hope my explanations help.
Text decoration affects the underline, not the color.
To set the visited color to the same as the default, try:
a {
color: blue;
}
Or
a {
text-decoration: none;
}
a:link, a:visited {
color: blue;
}
a:hover {
color: red;
}
Can you pick the appropriate char set in the Constructor:
new InputStreamReader(new FileInputStream(in), "ISO8859_1");
A simple js solution to set modal height proportional to body's height :
$(document).ready(function () {
$('head').append('<style type="text/css">.modal .modal-body {max-height: ' + ($('body').height() * .8) + 'px;overflow-y: auto;}.modal-open .modal{overflow-y: hidden !important;}</style>');
});
body's height has to be 100% :
html, body {
height: 100%;
min-height: 100%;
}
I set modal body height to 80% of body, this can be of course customized.
Hope it helps.
Check this out! It was built no longer ago in 2014.
Get a list of country/state/city in a hierarchy using geonames webservice
For question 1):
Considering that the error message doesn't seem to say which line of your code is causing the trouble, you can track it down by using breakpoints. Breakpoints pause the execution of the program when the program gets to specific lines of code. By adding breakpoints to critical locations, you can determine which line of code causes the crash. For example, if your program is crashing at a setContentView() line, you could put a breakpoint there. When the program runs, it will pause before running that line. If then resuming causes the program to crash before reaching the next breakpoint, you then know that the line that killed the program was between the two breakpoints.
Adding breakpoints is easy if you're using Eclipse. Right click in the margin just to the left of your code and select "Toggle breakpoint". You then need to run your application in debug mode, the button that looks like a green insect next to the normal run button. When the program hits a breakpoint, Eclipse will switch to the debug perspective and show you the line it is waiting at. To start the program running again, look for the 'Resume' button, which looks like a normal 'Play' but with a vertical bar to the left of the triangle.
You can also fill your application with Log.d("My application", "Some information here that tells you where the log line is"), which then posts messages in Eclipse's LogCat window. If you can't find that window, open it up with Window -> Show View -> Other... -> Android -> LogCat.
Hope that helps!
Quick Update, effective from February 15th, 2015, we cannot submit apps to the store that were developed using an SDK prior to iOS 8. So, keeping that in mind , its better to not to worry about this issue as many people have suggested that apps made in Swift can be deployed to OS X 10.9 and iOS 7.0 as well.
Both methods do the same functionally - they compare values.
As is written on MSDN:
String.Equals
method - Determines whether this instance and
another specified String object have the same value. (http://msdn.microsoft.com/en-us/library/858x0yyx.aspx)==
- Although string is a reference type, the equality operators (==
and
!=
) are defined to compare the values of string objects, not
references. This makes testing for string equality more intuitive. (http://msdn.microsoft.com/en-en/library/362314fe.aspx)But if one of your string instances is null, these methods are working differently:
string x = null;
string y = "qq";
if (x == y) // returns false
MessageBox.Show("true");
else
MessageBox.Show("false");
if (x.Equals(y)) // returns System.NullReferenceException: Object reference not set to an instance of an object. - because x is null !!!
MessageBox.Show("true");
else
MessageBox.Show("false");
Run yarn cache clean
.
Run yarn help cache
in your bash, and you will see:
Usage: yarn cache [ls|clean] [flags]
Options: -h, --help output usage information -V, --version output the version number --offline
--prefer-offline
--strict-semver
--json
--global-folder [path]
--modules-folder [path] rather than installing modules into the node_modules folder relative to the cwd, output them here
--packages-root [path] rather than storing modules into a global packages root, store them here
--mutex [type][:specifier] use a mutex to ensure only one yarn instance is executingVisit http://yarnpkg.com/en/docs/cli/cache for documentation about this command.
I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).
JSON.parse(JSON.stringify(json_original));
Documentation
For those like me, who were looking for a pure Python solution without pandas
or numpy
involved, check out the following GitHub project: https://github.com/ThomIves/MatrixInverse.
It generously provides a very good explanation of how the process looks like "behind the scenes". The author has nicely described the step-by-step approach and presented some practical examples, all easy to follow.
This is just a little code snippet from there to illustrate the approach very briefly (AM
is the source matrix, IM
is the identity matrix of the same size):
def invert_matrix(AM, IM):
for fd in range(len(AM)):
fdScaler = 1.0 / AM[fd][fd]
for j in range(len(AM)):
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
crScaler = AM[i][fd]
for j in range(len(AM)):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
But please do follow the entire thing, you'll learn a lot more than just copy-pasting this code! There's a Jupyter notebook as well, btw.
Hope that helps someone, I personally found it extremely useful for my very particular task (Absorbing Markov Chain) where I wasn't able to use any non-standard packages.
You can use preg_replace in this case;
$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );
$res return 6 in this case.
If want also to include decimal separator or thousand separator check this example:
$res = preg_replace("/[^0-9.]/", "", "$ 123.099");
$res returns "123.099" in this case
Include period as decimal separator or thousand separator: "/[^0-9.]/"
Include coma as decimal separator or thousand separator: "/[^0-9,]/"
Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"
In javascript there are no block-level scopes
only function-level scopes
:
Read this article about javaScript Scoping and Hoisting.
var deferred = $q.defer();
deferred.count = i;
console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects
// some code
.success(function(data){
console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object
deferred.resolve(data);
})
var deferred= $q.defer();
inside a for loop it's hoisted to the top of the function, it means that javascript declares this variable on the function scope outside of the for loop
.closure scope
even after functions are executed.angular.forEach
:Here is a demo plunker: http://plnkr.co/edit/NGMp4ycmaCqVOmgohN53?p=preview
UploadService.uploadQuestion = function(questions){
var promises = [];
angular.forEach(questions , function(question) {
var promise = $http({
url : 'upload/question',
method: 'POST',
data : question
});
promises.push(promise);
});
return $q.all(promises);
}
Array#map
:Here is a demo plunker: http://plnkr.co/edit/KYeTWUyxJR4mlU77svw9?p=preview
UploadService.uploadQuestion = function(questions){
var promises = questions.map(function(question) {
return $http({
url : 'upload/question',
method: 'POST',
data : question
});
});
return $q.all(promises);
}
You put the if
at the end:
[y for y in a if y not in b]
List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:
outputlist = []
for y in a:
if y not in b:
outputlist.append(y)
Your version tried to do this instead:
outputlist = []
if y not in b:
for y in a:
outputlist.append(y)
but a list comprehension must start with at least one outer loop.
Let us talk about them in the context of Java history ;
List
: List means it can include any Object. List was in the release before Java 5.0; Java 5.0 introduced List, for backward compatibility.
List list=new ArrayList();
list.add(anyObject);
List<?>
: ?
means unknown Object not any Object; the wildcard ?
introduction is for solving the problem built by Generic Type; see wildcards;
but this also causes another problem:
Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error
List< T> List< E>
Means generic Declaration at the premise of none T or E type in your project Lib.
List< Object>
means generic parameterization.The easiest of all the above ways is to:
Voila!
Note that this will not work if your password is in your URL itself. If that is the case then you need to follow the steps given by @moleksyuk here
You also choose to use the credentials helper option in IntelliJ to achieve similar functionality as suggested by Ramesh here
int filesCount = Directory.EnumerateFiles(Directory).Count();
I think both the fastest and most concise way to do this is to use NumPy's built-in Fancy indexing. If you have an ndarray
named arr
, you can replace all elements >255
with a value x
as follows:
arr[arr > 255] = x
I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.
In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit A[A > 0.5] = 5
100 loops, best of 3: 7.59 ms per loop
First, run npm install expo-linear-gradient --save
You don't need to use an animated tag, but this is what I was using in my code.
inside colors={[ put your gradient colors ]}
then you can use something like this:
import { LinearGradient } from "expo-linear-gradient";
import { Animated } from "react-native";
<AnimatedLinearGradient
colors={["rgba(255,255,255, 0)", "rgba(255,255,255, 1)"]}
style={{ your styles go here }}/>
const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);
Add the same color of the background to the paragraph and then invert with CSS:
div {_x000D_
background-color: #f00;_x000D_
}_x000D_
_x000D_
p { _x000D_
color: #f00;_x000D_
-webkit-filter: invert(100%);_x000D_
filter: invert(100%);_x000D_
}
_x000D_
<div>_x000D_
<p>inverted color</p>_x000D_
</div>
_x000D_
Angular 10:
<video [muted]="true" [autoplay]="true" [loop]="true">
<source src="/assets/video.mp4" type="video/mp4"/>
</video>
First, make sure the listener on database server (computer A) that receives client connection requests is running. To do so, run lsnrctl status
command.
In case, if you get TNS:no listener
message (see below image), it means listener service is not running. To start it, run lsnrctl start
command.
Second, for database operations and connectivity from remote clients, the following executables must be added to the Windows Firewall exception list: (see image)
Oracle_home\bin\oracle.exe - Oracle Database executable
Oracle_home\bin\tnslsnr.exe - Oracle Listener
Finally, install oracle instant client on client machine (computer B) and run:
sqlplus user/password@computerA:port/XE
This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.
What about using extension method?
public static class StringExtensions
{
public static string Repeat(this char chatToRepeat, int repeat) {
return new string(chatToRepeat,repeat);
}
public static string Repeat(this string stringToRepeat,int repeat)
{
var builder = new StringBuilder(repeat*stringToRepeat.Length);
for (int i = 0; i < repeat; i++) {
builder.Append(stringToRepeat);
}
return builder.ToString();
}
}
You could then write :
Debug.WriteLine('-'.Repeat(100)); // For Chars
Debug.WriteLine("Hello".Repeat(100)); // For Strings
Note that a performance test of using the stringbuilder version for simple characters instead of strings gives you a major preformance penality :
on my computer the difference in mesured performance is 1:20 between:
Debug.WriteLine('-'.Repeat(1000000)) //char version and
Debug.WriteLine("-".Repeat(1000000)) //string version
What would you like these support libraries to do? Just using OpenGL from C# is simple enough and does not require any additional libraries afaik.
If you are doing light validation, it is best to do it on the client. It will save the network traffic which will help your server perform better. If if it complicated validation that involves pulling data from a database or something, like passwords, then it best to do it on the server where the data can be securely checked.
Useful for grid sorting this method sorts list based on property names. As follow the example.
List<MeuTeste> temp = new List<MeuTeste>();
temp.Add(new MeuTeste(2, "ramster", DateTime.Now));
temp.Add(new MeuTeste(1, "ball", DateTime.Now));
temp.Add(new MeuTeste(8, "gimm", DateTime.Now));
temp.Add(new MeuTeste(3, "dies", DateTime.Now));
temp.Add(new MeuTeste(9, "random", DateTime.Now));
temp.Add(new MeuTeste(5, "call", DateTime.Now));
temp.Add(new MeuTeste(6, "simple", DateTime.Now));
temp.Add(new MeuTeste(7, "silver", DateTime.Now));
temp.Add(new MeuTeste(4, "inn", DateTime.Now));
SortList(ref temp, SortDirection.Ascending, "MyProperty");
private void SortList<T>(
ref List<T> lista
, SortDirection sort
, string propertyToOrder)
{
if (!string.IsNullOrEmpty(propertyToOrder)
&& lista != null
&& lista.Count > 0)
{
Type t = lista[0].GetType();
if (sort == SortDirection.Ascending)
{
lista = lista.OrderBy(
a => t.InvokeMember(
propertyToOrder
, System.Reflection.BindingFlags.GetProperty
, null
, a
, null
)
).ToList();
}
else
{
lista = lista.OrderByDescending(
a => t.InvokeMember(
propertyToOrder
, System.Reflection.BindingFlags.GetProperty
, null
, a
, null
)
).ToList();
}
}
}
From looking at the source code, it seems like the pg_stat_database query gives you the number of connections to the current database for all users. On the other hand, the pg_stat_activity query gives the number of connections to the current database for the querying user only.
You didn't open the file in binary mode.
open("Fruits.obj",'rb')
Should work.
For your second error, the file is most likely empty, which mean you inadvertently emptied it or used the wrong filename or something.
(This is assuming you really did close your session. If not, then it's because you didn't close the file between the write and the read).
I tested your code, and it works.
This will draw a line that passes through the points (-1, 1) and (12, 4), and another one that passes through the points (1, 3) et (10, 2)
x1 are the x coordinates of the points for the first line, y1 are the y coordinates for the same -- the elements in x1 and y1 must be in sequence.
x2 and y2 are the same for the other line.
import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 4]
x2, y2 = [1, 10], [3, 2]
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()
I suggest you spend some time reading / studying the basic tutorials found on the very rich matplotlib website to familiarize yourself with the library.
There are no direct ways to have lines extend to infinity... matplotlib will either resize/rescale the plot so that the furthest point will be on the boundary and the other inside, drawing line segments in effect; or you must choose points outside of the boundary of the surface you want to set visible, and set limits for the x and y axis.
As follows:
import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 10]
x2, y2 = [-1, 10], [3, -1]
plt.xlim(0, 8), plt.ylim(-2, 8)
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()
As mentioned in the comments, some labels in y_test
don't appear in y_pred
. Specifically in this case, label '2' is never predicted:
>>> set(y_test) - set(y_pred)
{2}
This means that there is no F-score to calculate for this label, and thus the F-score for this case is considered to be 0.0. Since you requested an average of the score, you must take into account that a score of 0 was included in the calculation, and this is why scikit-learn is showing you that warning.
This brings me to you not seeing the error a second time. As I mentioned, this is a warning, which is treated differently from an error in python. The default behavior in most environments is to show a specific warning only once. This behavior can be changed:
import warnings
warnings.filterwarnings('always') # "error", "ignore", "always", "default", "module" or "once"
If you set this before importing the other modules, you will see the warning every time you run the code.
There is no way to avoid seeing this warning the first time, aside for setting warnings.filterwarnings('ignore')
. What you can do, is decide that you are not interested in the scores of labels that were not predicted, and then explicitly specify the labels you are interested in (which are labels that were predicted at least once):
>>> metrics.f1_score(y_test, y_pred, average='weighted', labels=np.unique(y_pred))
0.91076923076923078
The warning is not shown in this case.
You can use tee
to write to the file without the need for flushing.
/homedir/MyScript 2>&1 | tee some_log.log > /dev/null
Follow the link below and configure it to what you need. Daterangepicker does it for you, very easily. :)
BE VERY CAREFUL, the problem may come from multibytes encoding and inappropriate PHP functions used...
It was the case for me and it took me a while to figure it out.
For example, I get the a string from MySQL using utf8mb4 (very common now to encode emojis):
$formattedString = strtolower($stringFromMysql);
$strCleaned = iconv('UTF-8', 'utf-8//TRANSLIT', $formattedString); // WILL RETURN THE ERROR 'Detected an illegal character in input string'
The problem does not stand in
iconv()
but stands instrtolower()
in this case.
The appropriate way is to use Multibyte String Functions mb_strtolower()
instead of strtolower()
$formattedString = mb_strtolower($stringFromMysql);
$strCleaned = iconv('UTF-8', 'utf-8//TRANSLIT', $formattedString); // WORK FINE
More examples of this issue are available at this SO answer
PHP Manual on the Multibyte String
I was also a bit confused between adjustResize and adjustPan when I was a beginner. The definitions given above are correct.
AdjustResize : Main activity's content is resized to make room for soft input i.e keyboard
AdjustPan : Instead of resizing overall contents of the window, it only pans the content so that the user can always see what is he typing
AdjustNothing : As the name suggests nothing is resized or panned. Keyboard is opened as it is irrespective of whether it is hiding the contents or not.
I have a created a example for better understanding
Below is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Type Here"
app:layout_constraintTop_toBottomOf="@id/button1"/>
<Button
android:id="@+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/button2"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginBottom="@dimen/margin70dp"/>
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="@id/button1"
app:layout_constraintEnd_toStartOf="@id/button3"
android:layout_marginBottom="@dimen/margin70dp"/>
<Button
android:id="@+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button3"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/button2"
android:layout_marginBottom="@dimen/margin70dp"/>
</android.support.constraint.ConstraintLayout>
Here is the design view of the xml
AdjustResize Example below:
AdjustPan Example below:
AdjustNothing Example below:
I want to know the time to brute force for when the password is a dictionary word and also when it is not a dictionary word.
Ballpark figure: there are about 1,000,000 English words, and if a hacker can compute about 10,000 SHA-512 hashes a second (update: see comment by CodesInChaos, this estimate is very low), 1,000,000 / 10,000 = 100 seconds. So it would take just over a minute to crack a single-word dictionary password for a single user. If the user concatenates two dictionary words, you're in the area of a few days, but still very possible if the attacker is cares enough. More than that and it starts getting tough.
If the password is a truly random sequence of alpha-numeric characters, upper and lower case, then the number of possible passwords of length N is 60^N (there are 60 possible characters). We'll do the calculation the other direction this time; we'll ask: What length of password could we crack given a specific length of time? Just use this formula:
N = Log60(t * 10,000)
where t is the time spent calculating hashes in seconds (again assuming 10,000 hashes a second).
1 minute: 3.2
5 minute: 3.6
30 minutes: 4.1
2 hours: 4.4
3 days: 5.2
So given a 3 days we'd be able to crack the password if it's 5 characters long.
This is all very ball-park, but you get the idea. Update: see comment below, it's actually possible to crack much longer passwords than this.
Let's clear up some misconceptions:
The salt doesn't make it slower to calculate hashes, it just means they have to crack each user's password individually, and pre-computed hash tables (buzz-word: rainbow tables) are made completely useless. If you don't have a precomputed hash-table, and you're only cracking one password hash, salting doesn't make any difference.
SHA-512 isn't designed to be hard to brute-force. Better hashing algorithms like BCrypt, PBKDF2 or SCrypt can be configured to take much longer to compute, and an average computer might only be able to compute 10-20 hashes a second. Read This excellent answer about password hashing if you haven't already.
update: As written in the comment by CodesInChaos, even high entropy passwords (around 10 characters) could be bruteforced if using the right hardware to calculate SHA-512 hashes.
The accepted answer as of September 2014 is incorrect and dangerously wrong:
In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack)... Finding a collision using a birthday attack takes O(2^n/2) time, where n is the output length of the hash function in bits.
The birthday attack is completely irrelevant to cracking a given hash. And this is in fact a perfect example of a preimage attack. That formula and the next couple of paragraphs result in dangerously high and completely meaningless values for an attack time. As demonstrated above it's perfectly possible to crack salted dictionary passwords in minutes.
The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords...
That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5...
Yes, please use an algorithm that is slow to compute, but what is "entropy-enducing"? Putting a low entropy password through a hash doesn't increase entropy. It should preserve entropy, but you can't make a rubbish password better with a hash, it doesn't work like that. A weak password put through PBKDF2 is still a weak password.
request parameter exist for both GET and POST ,For Get it will get appended as query string to URL but for POST it is within Request Body
In SUSE Linux Enterprise Server (SLES) and openSUSE the global one is located at /etc/vimrc
.
To edit it, simply do vi /etc/vimrc
.
In main.xml file
You can put the following attrubute to validate only alphabatics character can accept in edittext.
Do this :
android:entries="abcdefghijklmnopqrstuvwxyz"
SUMMARY: In ASP.NET, every Web page derives from the System.Web.UI.Page class. The Page class aggregates an instance of the HttpSession object for session data. The Page class exposes different events and methods for customization. In particular, the OnInit method is used to set the initialize state of the Page object. If the request does not have the Session cookie, a new Session cookie will be issued to the requester.
EDIT:
Session: A Concept for Beginners
SUMMARY: Session is created when user sends a first request to the server for any page in the web application, the application creates the Session and sends the Session ID back to the user with the response and is stored in the client machine as a small cookie. So ideally the "machine that has disabled the cookies, session information will not be stored".
I was unable to access to S3 because
Solution: rm -rf .aws/credentials
, then aws
uses role.
It seems like what you're looking for is a variant on the CSS Holy Grail Layout, but in two columns. Check out the resources at this answer for more information.
Leveraging David Dehghan's answer above, the following works in Python 2.7.13:
from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(290, 720, "Hello world")
can.save()
#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader("original.pdf")
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = open("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()
This is an issue in the Chrome family and has been there forever.
A bug has been raised https://bugs.chromium.org/p/chromium/issues/detail?id=904208
It can be shown here: https://codepen.io/anon/pen/Jedvwj as soon as you add a border to anything button-like (say role="button" has been added to a tag for example) Chrome messes up and sets the focus state when you click with your mouse.
I highly recommend using this fix: https://github.com/wicg/focus-visible.
Just do the following
npm install --save focus-visible
Add the script to your html:
<script src="/node_modules/focus-visible/dist/focus-visible.min.js"></script>
or import into your main entry file if using webpack or something similar:
import 'focus-visible/dist/focus-visible.min';
then put this in your css file:
// hide the focus indicator if element receives focus via mouse, but show on keyboard focus (on tab).
.js-focus-visible :focus:not(.focus-visible) {
outline: none;
}
// Define a strong focus indicator for keyboard focus.
// If you skip this then the browser's default focus indicator will display instead
// ideally use outline property for those users using windows high contrast mode
.js-focus-visible .focus-visible {
outline: magenta auto 5px;
}
You can just set:
button:focus {outline:0;}
but if you have a large number of users, you're disadvantaging those who cannot use mice or those who just want to use their keyboard for speed.
$ cat foo
1
2
3
4
5
$ sed -e '2d;4d' foo
1
3
5
$
"Reset" is the way to undo changes locally. When committing, you first select changes to include with "git add"--that's called "staging." And once the changes are staged, then you "git commit" them.
To back out from either the staging or the commit, you "reset" the HEAD. On a branch, HEAD is a git variable that points to the most recent commit. So if you've staged but haven't committed, you "git reset HEAD." That backs up to the current HEAD by taking changes off the stage. It's shorthand for "git reset --mixed HEAD~0."
If you've already committed, then the HEAD has already advanced, so you need to back up to the previous commit. Here you "reset HEAD~1" or "reset HEAD^1" or "reset HEAD~" or "reset HEAD^"-- all reference HEAD minus one.
Which is the better symbol, ~ or ^? Think of the ~ tilde as a single stream -- when each commit has a single parent and it's just a series of changes in sequence, then you can reference back up the stream using the tilde, as HEAD~1, HEAD~2, HEAD~3, for parent, grandparent, great-grandparent, etc. (technically it's finding the first parent in earlier generations).
When there's a merge, then commits have more than one parent. That's when the ^ caret comes into play--you can remember because it shows the branches coming together. Using the caret, HEAD^1 would be the first parent and HEAD^2 would be the second parent of a single commit--mother and father, for example.
So if you're just going back one hop on a single-parent commit, then HEAD~ and HEAD^ are equivalent--you can use either one.
Also, the reset can be --soft, --mixed, or --hard. A soft reset just backs out the commit--it resets the HEAD, but it doesn't check out the files from the earlier commit, so all changes in the working directory are preserved. And --soft reset doesn't even clear the stage (also known as the index), so all the files that were staged will still be on stage.
A --mixed reset (the default) also does not check out the files from the earlier commit, so all changes are preserved, but the stage is cleared. That's why a simple "git reset HEAD" will clear off the stage.
A --hard reset resets the HEAD, and it clears the stage, but it also checks out all the files from the earlier commit and so it overwrites any changes.
If you've pushed the commit to a remote repository, then reset doesn't work so well. You can reset locally, but when you try to push to the remote, git will see that your local HEAD is behind the HEAD in the remote branch and will refuse to push. You may be able to force the push, but git really does not like doing that.
Alternatively, you can stash your changes if you want to keep them, check out the earlier commit, un-stash the changes, stage them, create a new commit, and then push that.
since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.
df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,
or alternatively
df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters
You can now (as of Webpack v5.0.0) specify a unique output path for each entry using the new "descriptor" syntax (https://webpack.js.org/configuration/entry-context/#entry-descriptor) –
module.exports = {
entry: {
home: { import: './home.js', filename: 'unique/path/1/[name][ext]' },
about: { import: './about.js', filename: 'unique/path/2/[name][ext]' }
}
};