You can use ContainsKey
:
if (dict.ContainsKey(key)) { ... }
or TryGetValue
:
dict.TryGetValue(key, out value);
Update: according to a comment the actual class here is not an IDictionary
but a PhysicalAddressDictionary
, so the methods are Contains
and TryGetValue
but they work in the same way.
Example usage:
PhysicalAddressEntry entry;
PhysicalAddressKey key = c.PhysicalAddresses[PhysicalAddressKey.Home].Street;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
row["HomeStreet"] = entry;
}
Update 2: here is the working code (compiled by question asker)
PhysicalAddressEntry entry;
PhysicalAddressKey key = PhysicalAddressKey.Home;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
if (entry.Street != null)
{
row["HomeStreet"] = entry.Street.ToString();
}
}
...with the inner conditional repeated as necessary for each key required. The TryGetValue is only done once per PhysicalAddressKey (Home, Work, etc).
Modify to suit your specifics, or make more generic as needed:
Private Sub CopyItOver()
Set NewBook = Workbooks.Add
Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub
I would do it this way, so you won't end up with duplicate entries if the script is run multiple times.
@echo off
SET NEWLINE=^& echo.
FIND /C /I "ns1.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^62.116.159.4 ns1.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
FIND /C /I "ns2.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^217.160.113.37 ns2.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
FIND /C /I "ns3.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^89.146.248.4 ns3.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
FIND /C /I "ns4.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^74.208.254.4 ns4.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
I think the problem you are facing is almost this: -
str = str.replace("-", ' ');
You need to re-assign the result of the replacement to str
, to see the reflected change.
From MSDN Javascript reference: -
The result of the replace method is a copy of stringObj after the specified replacements have been made.
To replace all the -
, you would need to use /g
modifier with a regex parameter: -
str = str.replace(/-/g, ' ');
You can use the following script:
var findclasses = _doc.DocumentNode.Descendants("div").Where(d =>
d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("float")
);
Even though its not directly related. But I found that the CALC code won't work if you do not put spaces properly.
So this did not work for me calc(#{$a}+7px)
But this worked calc(#{$a} + 7px)
Took me sometime to figure this out.
Do I really have to first convert it into an array of arrays of key-value pairs?
No, an iterator of key-value pair arrays is enough. You can use the following to avoid creating the intermediate array:
function* entries(obj) {
for (let key in obj)
yield [key, obj[key]];
}
const map = new Map(entries({foo: 'bar'}));
map.get('foo'); // 'bar'
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
function showButtons () { $('#b1, #b2, #b3').show(); }
</script>
<style type="text/css">
#b1, #b2, #b3 {
display: none;
}
</style>
</head>
<body>
<a href="#" onclick="showButtons();">Show me the money!</a>
<input type="submit" id="b1" value="B1" />
<input type="submit" id="b2" value="B2"/>
<input type="submit" id="b3" value="B3" />
</body>
</html>
There is no data types for that.. You need to store it as VARCHAR or TEXT only.. jsonObject.toString();
You can't change the color of the line (you can't specify different foreground colors for the same element, and the text and its decoration form a single element). However there are some tricks:
a:link, a:visited {text-decoration: none; color: red; border-bottom: 1px solid #006699; }
a:hover, a:active {text-decoration: none; color: red; border-bottom: 1px solid #1177FF; }
Also you can make some cool effects this way:
a:link {text-decoration: none; color: red; border-bottom: 1px dashed #006699; }
Hope it helps.
here you are adding the foreign key for your "Child" table
ALTER TABLE child
ADD FOREIGN KEY (P_Id)
REFERENCES parent(P_Id)
ON DELETE CASCADE
ON UPDATE CASCADE;
After that if you make a DELETE query on "Parent" table like this
DELETE FROM parent WHERE .....
since the child has a reference to parent with DELETE CASCADE, the "Child" rows also will be deleted! along with the "parent".
Apache Cayanne ORM has an "In memory evaluation"
It may not work for unmapped object, but looks promising:
Expression exp = ExpressionFactory.likeExp("artistName", "A%");
List startWithA = exp.filterObjects(artists);
To solve your other problem, where you need to set scrolled
if the user scrolls manually, you'd have to attach a handler to the window scroll event. Generally this is a bad idea as the handler will fire a lot, a common technique is to set a timeout, like so:
var timer = 0;
$(window).scroll(function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
scrolled = $(window).scrollTop();
}, 250);
});
Check the character set of both projects in Configuration Properties ? General ? Character Set.
My UnitTest project was using the default character set Multi-Byte while my libraries were in Unicode.
My function was using a TCHAR as a parameter.
As a result, in my library my TCHAR was transformed into a WCHAR, but it was a char* in my UnitTest: the symbol was different because the parameters were really not the same in the end.
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
This works fine for me. It allows value to be entered even after focus changed and retrieved back. For example: 123.00
, 12.12
, 0.01
, etc..
1.Integer.parseInt(getString(R.string.valuelength))
Specifies the length of the input digits.Values
accessed from string.xml
file.It is quiet easy to change values.
2.Integer.parseInt(getString(R.string.valuedecimal))
, this is for decimal places max limit.
private InputFilter[] valDecimalPlaces;
private ArrayList<EditText> edittextArray;
valDecimalPlaces = new InputFilter[] { new DecimalDigitsInputFilterNew(
Integer.parseInt(getString(R.string.valuelength)),
Integer.parseInt(getString(R.string.valuedecimal)))
};
Array of EditText
values that allows to perform action.
for (EditText etDecimalPlace : edittextArray) {
etDecimalPlace.setFilters(valDecimalPlaces);
I just used array of values that contain multiple edittext
Next DecimalDigitsInputFilterNew.class
file.
import android.text.InputFilter;
import android.text.Spanned;
public class DecimalDigitsInputFilterNew implements InputFilter {
private final int decimalDigits;
private final int before;
public DecimalDigitsInputFilterNew(int before ,int decimalDigits) {
this.decimalDigits = decimalDigits;
this.before = before;
}
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches("(([0-9]{1})([0-9]{0,"+(before-1)+"})?)?(\\.[0-9]{0,"+decimalDigits+"})?")) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
}
the case above is for a new project. I hit upon this error while editing a fork of a well established library.
the typedef was included in the file I was editing but the struct wasn't.
The end result being that I was attempting to edit the struct in the wrong place.
If you run into this in a similar way look for other places where the struct is edited and try it there.
pow() doesn't work with int
, hence the error "error C2668:'pow': ambiguous call to overloaded function"
http://www.cplusplus.com/reference/clibrary/cmath/pow/
Write your own power function for int
s:
int power(int base, int exp)
{
int result = 1;
while(exp) { result *= base; exp--; }
return result;
}
On Linux and other UNIX / UNIX-like platforms, the OS places a limit on the number of open file descriptors that a process may have at any given time. In the old days, this limit used to be hardwired1, and relatively small. These days it is much larger (hundreds / thousands), and subject to a "soft" per-process configurable resource limit. (Look up the ulimit
shell builtin ...)
Your Java application must be exceeding the per-process file descriptor limit.
You say that you have 19 files open, and that after a few hundred times you get an IOException saying "too many files open". Now this particular exception can ONLY happen when a new file descriptor is requested; i.e. when you are opening a file (or a pipe or a socket). You can verify this by printing the stacktrace for the IOException.
Unless your application is being run with a small resource limit (which seems unlikely), it follows that it must be repeatedly opening files / sockets / pipes, and failing to close them. Find out why that is happening and you should be able to figure out what to do about it.
FYI, the following pattern is a safe way to write to files that is guaranteed not to leak file descriptors.
Writer w = new FileWriter(...);
try {
// write stuff to the file
} finally {
try {
w.close();
} catch (IOException ex) {
// Log error writing file and bail out.
}
}
1 - Hardwired, as in compiled into the kernel. Changing the number of available fd slots required a recompilation ... and could result in less memory being available for other things. In the days when Unix commonly ran on 16-bit machines, these things really mattered.
UPDATE
The Java 7 way is more concise:
try (Writer w = new FileWriter(...)) {
// write stuff to the file
} // the `w` resource is automatically closed
UPDATE 2
Apparently you can also encounter a "too many files open" while attempting to run an external program. The basic cause is as described above. However, the reason that you encounter this in exec(...)
is that the JVM is attempting to create "pipe" file descriptors that will be connected to the external application's standard input / output / error.
It appears I cannot use an if statement.
Arrow functions either allow to use an expression or a block as their body. Passing an expression
foo => bar
is equivalent to the following block
foo => { return bar; }
However,
if (person.age > 18) person
is not an expression, if
is a statement. Hence you would have to use a block, if you wanted to use if
in an arrow function:
foo => { if (person.age > 18) return person; }
While that technically solves the problem, this a confusing use of .filter
, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to .filter
should return a Boolean, i.e. true
or false
, indicating whether the element should be included in the new array or not.
So all you need is
family.filter(person => person.age > 18);
In ES5:
family.filter(function (person) {
return person.age > 18;
});
I was able to convert pem to crt using this:
openssl x509 -outform der -in your-cert.pem -out your-cert.crt
Try casting to List in the extension method before running the loop. That way you can take advantage of the performance of List.AddRange.
public static void AddRange<T>(this ICollection<T> destination,
IEnumerable<T> source)
{
List<T> list = destination as List<T>;
if (list != null)
{
list.AddRange(source);
}
else
{
foreach (T item in source)
{
destination.Add(item);
}
}
}
Input String
[
{
"userName": "sandeep",
"age": 30
},
{
"userName": "vivan",
"age": 5
}
]
Simple Way to Convert String to JSON
public class Test
{
public static void main(String[] args) throws JSONException
{
String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}] ";
JSONArray jsonArr = new JSONArray(data);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println(jsonObj);
}
}
}
Output
{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}
Variables containing primitive types are passed by value in PHP5. Variables containing objects are passed by reference. There's quite an interesting article from Linux Journal from 2006 which mentions this and other OO differences between 4 and 5.
For those using spacemacs
, and ipython
that comes with python-layer
, save magic creates a lot of unwanted output, because of the constant auto-completion command working in the backround such as:
len(all_suffixes)
';'.join(__PYTHON_EL_get_completions('''len'''))
';'.join(__PYTHON_EL_get_completions('''all_substa'''))
len(all_substantives_w_suffixes)
';'.join(__PYTHON_EL_get_completions('''len'''))
';'.join(__PYTHON_EL_get_completions('''all'''))
';'.join(__PYTHON_EL_get_completions('''all_'''))
';'.join(__PYTHON_EL_get_completions('''all_w'''))
';'.join(__PYTHON_EL_get_completions('''all_wo'''))
';'.join(__PYTHON_EL_get_completions('''all_wor'''))
';'.join(__PYTHON_EL_get_completions('''all_word'''))
';'.join(__PYTHON_EL_get_completions('''all_words'''))
len(all_words_w_logograms)
len(all_verbs)
To avoid this just save the ipython buffer like you normally save any other: spc f s
Here are some high level thoughts and info that might help, aside from the other answers.
Pollyfills are like a compatability patch for specific browsers. Shims are changes to specific arguments. Fallbacks can be used if say a @mediaquery is not compatible with a browser.
It kind of depends on the requirements of what your app/website needs to be compatible with.
You cna check this site out for compatability of specific libraries with specific browsers. https://caniuse.com/
Late reply, but consider addressing the problem in this way, using the bash builtin read as illustrated within the code snippet from a ufw firewall script that follows. This approach has the advantage of using as many delimited field sets (not just 2) as are desired. We have used the | delimiter because port range specifiers may require a colon, ie 6001:6010.
#!/usr/bin/env bash
readonly connections=(
'192.168.1.4/24|tcp|22'
'192.168.1.4/24|tcp|53'
'192.168.1.4/24|tcp|80'
'192.168.1.4/24|tcp|139'
'192.168.1.4/24|tcp|443'
'192.168.1.4/24|tcp|445'
'192.168.1.4/24|tcp|631'
'192.168.1.4/24|tcp|5901'
'192.168.1.4/24|tcp|6566'
)
function set_connections(){
local range proto port
for fields in ${connections[@]}
do
IFS=$'|' read -r range proto port <<< "$fields"
ufw allow from "$range" proto "$proto" to any port "$port"
done
}
set_connections
I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(
//open upload window upload.click();
//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);
FWIW, I got this same error when I forgot to set the cell identifier in the storyboard. If this is your issue then in the storyboard click the table view cell and set the cell identifier in the attributes editor. Make sure the cell identifier you set here is the same as
static NSString *CellIdentifier = @"YourCellIdenifier";
use box-shadow
with no horizontal offset.
http://www.css3.info/preview/box-shadow/
eg.
div {_x000D_
-webkit-box-shadow: 0 10px 5px #888888;_x000D_
-moz-box-shadow: 0 10px 5px #888888;_x000D_
box-shadow: 0 10px 5px #888888;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
There will be a slight shadow on the sides with a large blur radius (5px in above example)
It's not the angular way, remove the function from html body and use it in controller, or use
angular.element(document).ready
More details are available here: https://stackoverflow.com/a/18646795/4301583
+
means "one or more characters" and without the plus it means "one character." In your case both result in the same output.
I got this error after change a loop in my program, let`s see:
for ...
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:
for ...
x_batch = []
y_batch = []
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
Then, check if you are using np.asarray() or something like that.
I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/
Ive refactored the code to make it simpler for this.
// In your controller
var w = angular.element($window);
$scope.$watch(
function () {
return $window.innerWidth;
},
function (value) {
$scope.windowWidth = value;
},
true
);
w.bind('resize', function(){
$scope.$apply();
});
You can then reference to windowWidth from the html
<span ng-bind="windowWidth"></span>
This normally requires you to know ALL the column AND row labels beforehand. As you can see in the query below, the labels are all listed in their entirely in both the UNPIVOT and the (re)PIVOT operations.
MS SQL Server 2012 Schema Setup:
create table tbl (
color varchar(10), Paul int, John int, Tim int, Eric int);
insert tbl select
'Red' ,1 ,5 ,1 ,3 union all select
'Green' ,8 ,4 ,3 ,5 union all select
'Blue' ,2 ,2 ,9 ,1;
Query 1:
select *
from tbl
unpivot (value for name in ([Paul],[John],[Tim],[Eric])) up
pivot (max(value) for color in ([Red],[Green],[Blue])) p
| NAME | RED | GREEN | BLUE |
-----------------------------
| Eric | 3 | 5 | 1 |
| John | 5 | 4 | 2 |
| Paul | 1 | 8 | 2 |
| Tim | 1 | 3 | 9 |
I believe app:itemBackground
expects a drawable. So follow the steps below :
Make a drawable file highlight_color.xml
with following contents :
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="YOUR HIGHLIGHT COLOR"/>
</shape>
Make another drawable file nav_item_drawable.xml
with following contents:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/highlight_color" android:state_checked="true"/>
</selector>
Finally add app:itemBackground
tag in the NavView :
<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
app:itemBackground="@drawable/nav_item_drawable"
app:menu="@menu/menu_drawer">
here the highlight_color.xml file defines a solid color drawable for the background. Later this color drawable is assigned to nav_item_drawable.xml selector.
This worked for me. Hopefully this will help.
********************************************** UPDATED **********************************************
Though the above mentioned answer gives you fine control over some properties, but the way I am about to describe feels more SOLID and is a bit COOLER.
So what you can do is, you can define a ThemeOverlay in the styles.xml
for the NavigationView like this :
<style name="ThemeOverlay.AppCompat.navTheme">
<!-- Color of text and icon when SELECTED -->
<item name="colorPrimary">@color/color_of_your_choice</item>
<!-- Background color when SELECTED -->
<item name="colorControlHighlight">@color/color_of_your_choice</item>
</style>
now apply this ThemeOverlay to app:theme
attribute of NavigationView, like this:
<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:theme="@style/ThemeOverlay.AppCompat.navTheme"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/menu_drawer">
I hope this will help.
Update Model from Database doesn't works for me.
I had to remove the conflicted entity, then execute Update Model from Database, lastly rebuild the solution. After that, everything works fine.
If you go to your android-sdk/tools
folder I think you'll find a message :
The adb tool has moved to platform-tools/
If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"
Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.
So you should also add C:/android-sdk/platform-tools
to you environment path. Also after you modify the PATH
variable make sure that you start a new CommandPrompt
window.
for me I was naming branch as
Rel4.6/bug/Some-short-description
all I had to do is when using
git push origin Relx.x/bug/Some-short-description
to write
git push origin relx.x/bug/Some-short-description
as I used to create branches using small letter r in rel.
so, what caused this issue?
when I listed .git/refs/heads
content I found
drwxr-xr-x 4 eslam_khoga staff 128B Sep 22 20:22 relx.x
but no Relx.x
!
and inside it bug
and inside bug
my branch's name.
So, git try to create a dir with same name but different case letters
but system is not case sensitive.
That's what caused this issue!
When git push [$there]
does not say what to push, we have used the
traditional "matching" semantics so far (all your branches were sent
to the remote as long as there already are branches of the same name
over there). In Git 2.0, the default is now the "simple" semantics,
which pushes:
only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or
only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.
You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.
When git add -u
and git add -A
are run inside a subdirectory
without specifying which paths to add on the command line, they
operate on the entire tree for consistency with git commit -a
and
other commands (these commands used to operate only on the current
subdirectory). Say git add -u .
or git add -A .
if you want to
limit the operation to the current directory.
git add <path>
is the same as git add -A <path>
now, so that
git add dir/
will notice paths you removed from the directory and
record the removal. In older versions of Git, git add <path>
used
to ignore removals. You can say git add --ignore-removal <path>
to
add only added or modified paths in <path>
, if you really want to.
As pointed out by michaelb958, you cannot replace in place with data of a different length because this will put the rest of the sections out of place. I disagree with the other posters suggesting you read from one file and write to another. Instead, I would read the file into memory, fix the data up, and then write it out to the same file in a separate step.
# Read in the file
with open('file.txt', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('ram', 'abcd')
# Write the file out again
with open('file.txt', 'w') as file:
file.write(filedata)
Unless you've got a massive file to work with which is too big to load into memory in one go, or you are concerned about potential data loss if the process is interrupted during the second step in which you write data to the file.
You can't. And it's a security measure. Imagine if someone writes JS that sets file input value to some sensitive data file?
HTML :
<div id="myDiv">
<form id="myForm">
</form>
</div>
jQuery :
var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';
$("#myDiv form#myForm").html(chbx);
//to insert dynamically created form
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");
The endroid/QrCode library is easy to use, well maintained, and can be installed using composer. There is also a bundle to use directly with Symfony.
Installing :
$ composer require endroid/qrcode
Usage :
<?php
use Endroid\QrCode\QrCode;
$qrCode = new QrCode();
$qrCode
->setText('Life is too short to be generating QR codes')
->setSize(300)
->setPadding(10)
->setErrorCorrection('high')
->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
->setLabel('Scan the code')
->setLabelFontSize(16)
->setImageType(QrCode::IMAGE_TYPE_PNG)
;
// now we can directly output the qrcode
header('Content-Type: '.$qrCode->getContentType());
$qrCode->render();
// or create a response object
$response = new Response($qrCode->get(), 200, array('Content-Type' => $qrCode->getContentType()));
Using the same center in the view and subview is the simplest way of doing it. You can do something like this,
UIView *innerView = ....;
innerView.view.center = self.view.center;
[self.view addSubView:innerView];
I had this other solution (I'm posting it in case someone else as me is using the following method from the model):
class onlyUserIsActiveField(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(onlyUserIsActiveField, self).__init__(*args, **kwargs)
self.fields['is_active'].initial = False
class Meta:
model = User
fields = ['is_active']
labels = {'is_active': 'Is Active'}
widgets = {
'is_active': forms.CheckboxInput( attrs={
'class': 'form-control bootstrap-switch',
'data-size': 'mini',
'data-on-color': 'success',
'data-on-text': 'Active',
'data-off-color': 'danger',
'data-off-text': 'Inactive',
'name': 'is_active',
})
}
The initial is definded on the __init__
function as self.fields['is_active'].initial = False
$('#navigation ul li').css({'display' : 'inline-block'});
It seems a typo there ...syntax mistake :))
People gave good answers but forgot to mention the most important part in my opinion:
In the second example the X
of the list comprehension is NOT the same as the X
of the lambda
function, they are totally unrelated.
So the second example is actually the same as:
[Lambda X: X*X for I in range(10)]
The internal iterations on range(10)
are only responsible for creating 10 similar lambda functions in a list (10 separate functions but totally similar - returning the power 2 of each input).
On the other hand, the first example works totally different, because the X of the iterations DO interact with the results, for each iteration the value is X*X
so the result would be [0,1,4,9,16,25, 36, 49, 64 ,81]
This got bumped to the top because of an edit ... The answers have gotten a bit stale, and not as useful today as another solution has been added to the standard.
There is now an "all" shorthand property.
#elementId select.funTimes {
all: initial;
}
This sets all css properties to their initial value ... note some of the initial values are inherit; Resulting in some formatting still taking place on the element.
Because of that pause required when reading the code or reviewing it in the future, don't use it unless you most as the review process is a point where errors/bugs can be made! when editing the page. But clearly if there are a large number of properties that need to be reset, then "all" is the way to go.
Standard is online here: https://drafts.csswg.org/css-cascade/#all-shorthand
mysql int types can do quite a few rows: http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html
unsigned int
largest value is 4,294,967,295
unsigned bigint
largest value is 18,446,744,073,709,551,615
I got the same error. In my case I had multiple div with same id in a page. I renamed the another id of the div used and fixed the issue.
So confirm whether the element:
There are many ways of doing this (and I encourage you to look them up as they will be more efficient generally) but the simplest way of doing this is to use a non-set operation to define the value of the third column:
SELECT
t1.previous
,t1.present
,(t1.present - t1.previous) as difference
FROM #TEMP1 t1
Note, this style of selection is considered bad practice because it requires the query plan to reselect the value of the first two columns to logically determine the third (a violation of set theory that SQL is based on). Though it is more complicated, if you plan on using this to evaluate more than the values you listed in your example, I would investigate using an APPLY clause. http://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx
I wanted a more concise answer and I came up with the following using the documentation at aggregates and group
db.countries.aggregate([{"$group": {"_id": "$country", "count":{"$sum": 1}}])
Both Oracle Data Provider for .NET (from Oracle) and .NET Framework Data Provider for Oracle (from Microsoft) require Oracle Client installed on machine.
Faced the same problem. 'conda update'
does not work; It gives the error : "CondaValueError: no package names supplied"
On executing the following commands, I was able to launch the Anaconda navigator:
conda update -n base conda
conda update anaconda-navigator
What we didn't do right was to not apply with the accurate code when signing in the Build Settings. We fixed the issue up this way: Enter into Build Settings >> Code Signing >> Code Sign Identity. Then, apply with your iOS Developer ID for 'Debug', but be sure to apply with your iOS Distribution Profile for 'Release' We didn't apply correctly, so we couldn't have permission to ask for the App from the server, actually. Anyway this post forced us to revise all the parameters and requirements, so we pretty appreciate all your answers. Regards, T.
Take a look here.
You should set the font of the button's titleLabel instead.
myButton.titleLabel!.font = UIFont(name: "...", 10)
If you want to use this with command line or function arguments, make sure you use size=${#1}
instead of size=${#$1}
. The second one may be more instinctual but is incorrect syntax.
Try this for PyQt5:
pip install PyQt5
Use the operating system on this link for PyQt4.
Or download the supported wheel for your platform on this link.
Else use this link for the windows executable installer. Hopefully this helps you to install either PyQt4 or PyQt5.
a = double.Parse(Console.ReadLine());
Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.
Edit:
To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.
If you'd like to perform some sort of error checking, simply do this:
if ( double.TryParse(Console.ReadLine(), out a) ) {
Console.Writeline("Sonuç "+ a * Math.PI;);
}
else {
Console.WriteLine("Invalid number entered. Please enter number in format: #.#");
}
Thanks to Öyvind and abatischev for helping me refine my answer.
Both of them increase the variable i
by one. It's like saying i = i + 1
. The difference is subtle. If you're using it in a loop like this, there's no difference:
for (int i = 0; i < 100; i++) {
}
for (int i = 0; i < 100; ++i) {
}
If you want to know the difference, look at this example:
int a = 0;
int b = a++; // b = 0; a = 1
a = 0;
b = ++a: // b = 1; a = 1
The idea is that ++a
increments a
and returns that value, while a++
returns a's value and then increments a
.
I don't believe Windows (as opposed to .NET) provides a direct way to get that.
The only way I know of is to enumerate all the top level windows with EnumWindows()
and then find what process each belongs to GetWindowThreadProcessID()
. This sounds indirect and inefficient, but it's not as bad as you might expect -- in a typical case, you might have a dozen top level windows to walk through...
You can use System Internals PSEXEC command to remotely execute a net stop yourservice, then net start yourservice
Give you a pagination component, which is maybe a little difficult to understand for newbie to react
:
Version 25.2.3 (and higher) of Android SDK Tools
package contains new tool - sdkmanager - which simplifies this task of installing build-tools from the command line.
It is located in android_sdk/tools/bin
folder.
Usage (from documentation):
sdkmanager packages [options]
The
packages
argument is an SDK-style path, wrapped in quotes (for example,"build-tools;25.0.0"
or"platforms;android-25"
). You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.
Example usage (on my Mac):
alex@mbpro:~/sdk/tools/bin$ ls ../../build-tools/
25.0.0/
alex@mbpro:~/sdk/tools/bin$ ./sdkmanager "build-tools;25.0.2"
done
alex@mbpro:~/sdk/tools/bin$ ls ../../build-tools/
25.0.0/ 25.0.2/
You can also specify various options, for example to force all connections to use HTTP (--no_https
), or in order to use proxy server (--proxy_host=address
and --proxy_port=port
).
To check the available options, use the --help
flag. On my machine (Mac), the output is as following:
alex@mbpro:~/sdk/tools/bin$ ./sdkmanager --help
Usage:
sdkmanager [--uninstall] [<common args>] \
[--package_file <package-file>] [<packages>...]
sdkmanager --update [<common args>]
sdkmanager --list [<common args>]
In its first form, installs, or uninstalls, or updates packages.
<package> is a sdk-style path (e.g. "build-tools;23.0.0" or
"platforms;android-23").
<package-file> is a text file where each line is a sdk-style path
of a package to install or uninstall.
Multiple --package_file arguments may be specified in combination
with explicit paths.
In its second form (with --update), currently installed packages are
updated to the latest version.
In its third form, all installed and available packages are printed out.
Common Arguments:
--sdk_root=<sdkRootPath>: Use the specified SDK root instead of the SDK containing this tool
--channel=<channelId>: Include packages in channels up to <channelId>.
Common channels are:
0 (Stable), 1 (Beta), 2 (Dev), and 3 (Canary).
--include_obsolete: With --list, show obsolete packages in the
package listing. With --update, update obsolete
packages as well as non-obsolete.
--no_https: Force all connections to use http rather than https.
--proxy=<http | socks>: Connect via a proxy of the given type.
--proxy_host=<IP or DNS address>: IP or DNS address of the proxy to use.
--proxy_port=<port #>: Proxy port to connect to.
* If the env var REPO_OS_OVERRIDE is set to "windows",
"macosx", or "linux", packages will be downloaded for that OS.
jqGrid is $299 if you use a special version that has server side integration, but it really is not that difficult to use the open source free version with ASP.NET MVC, once you get your jquery configuration straight it's almost as simple to use as any other licensed grid:
http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx
This is the way how I will debug:
CREATE PROCEDURE procedure_name()
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SHOW ERRORS; --this is the only one which you need
ROLLBACK;
END;
START TRANSACTION;
--query 1
--query 2
--query 3
COMMIT;
END
If query 1, 2 or 3 will throw an error, HANDLER will catch the SQLEXCEPTION and SHOW ERRORS will show errors for us. Note: SHOW ERRORS should be the first statement in the HANDLER.
var option = driver.FindElement(By.Id("employmentType"));
var selectElement = new SelectElement(option);
Task.Delay(3000).Wait();
selectElement.SelectByIndex(2);
Console.Read();
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:
From Apple iOS7 transition Guide,
Specifically,
self.automaticallyAdjustsScrollViewInsets = YES;
self.edgesForExtendedLayout = UIRectEdgeNone;
works for me when I don't want to overlap and I have a UITableViewController.
The best method to convert multiple images to PDF I have tried so far is to use PIL
purely. It's quite simple yet powerful:
from PIL import Image
im1 = Image.open("/Users/apple/Desktop/bbd.jpg")
im2 = Image.open("/Users/apple/Desktop/bbd1.jpg")
im3 = Image.open("/Users/apple/Desktop/bbd2.jpg")
im_list = [im2,im3]
pdf1_filename = "/Users/apple/Desktop/bbd1.pdf"
im1.save(pdf1_filename, "PDF" ,resolution=100.0, save_all=True, append_images=im_list)
Just set save_all
to True
and append_images
to the list of images which you want to add.
You might encounter the AttributeError: 'JpegImageFile' object has no attribute 'encoderinfo'
. The solution is here Error while saving multiple JPEGs as a multi-page PDF
Note:Install the newest PIL
to make sure save_all
argument is available for PDF.
By default any integral primitive data type (byte, short, int, long) will be treated as int type by java compiler. For byte and short, as long as value assigned to them is in their range, there is no problem and no suffix required. If value assigned to byte and short exceeds their range, explicit type casting is required.
Ex:
byte b = 130; // CE: range is exceeding.
to overcome this perform type casting.
byte b = (byte)130; //valid, but chances of losing data is there.
In case of long data type, it can accept the integer value without any hassle. Suppose we assign like
Long l = 2147483647; //which is max value of int
in this case no suffix like L/l is required. By default value 2147483647 is considered by java compiler is int type. Internal type casting is done by compiler and int is auto promoted to Long type.
Long l = 2147483648; //CE: value is treated as int but out of range
Here we need to put suffix as L to treat the literal 2147483648 as long type by java compiler.
so finally
Long l = 2147483648L;// works fine.
Found a good code with comments explaining each statement. Code found at - accessallinone
Sub DAOLooping()
On Error GoTo ErrorHandler
Dim strSQL As String
Dim rs As DAO.Recordset
strSQL = "tblTeachers"
'For the purposes of this post, we are simply going to make
'strSQL equal to tblTeachers.
'You could use a full SELECT statement such as:
'SELECT * FROM tblTeachers (this would produce the same result in fact).
'You could also add a Where clause to filter which records are returned:
'SELECT * FROM tblTeachers Where ZIPPostal = '98052'
' (this would return 5 records)
Set rs = CurrentDb.OpenRecordset(strSQL)
'This line of code instantiates the recordset object!!!
'In English, this means that we have opened up a recordset
'and can access its values using the rs variable.
With rs
If Not .BOF And Not .EOF Then
'We don’t know if the recordset has any records,
'so we use this line of code to check. If there are no records
'we won’t execute any code in the if..end if statement.
.MoveLast
.MoveFirst
'It is not necessary to move to the last record and then back
'to the first one but it is good practice to do so.
While (Not .EOF)
'With this code, we are using a while loop to loop
'through the records. If we reach the end of the recordset, .EOF
'will return true and we will exit the while loop.
Debug.Print rs.Fields("teacherID") & " " & rs.Fields("FirstName")
'prints info from fields to the immediate window
.MoveNext
'We need to ensure that we use .MoveNext,
'otherwise we will be stuck in a loop forever…
'(or at least until you press CTRL+Break)
Wend
End If
.close
'Make sure you close the recordset...
End With
ExitSub:
Set rs = Nothing
'..and set it to nothing
Exit Sub
ErrorHandler:
Resume ExitSub
End Sub
Recordsets have two important properties when looping through data, EOF (End-Of-File) and BOF (Beginning-Of-File). Recordsets are like tables and when you loop through one, you are literally moving from record to record in sequence. As you move through the records the EOF property is set to false but after you try and go past the last record, the EOF property becomes true. This works the same in reverse for the BOF property.
These properties let us know when we have reached the limits of a recordset.
This is my Python function:
def add_nulls(num, cnt=2):
cnt = cnt - len(str(num))
nulls = '0' * cnt
return '%s%s' % (nulls, num)
You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.
>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23
Or, as @PhillipCloud suggested, just days.astype(int)
since the timedelta
is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D'
, 'ns'
, ...).
You can find more about it here.
In Linux Mint 18 Cinnamon be sure to check /etc/profile.d/jdk_home.sh I renamed this file to jdk_home.sh.old and now my path does not keep getting overridden and I can call java -version and see Java 9 as expected. Even though I correctly selected Java 9 in update-aternatives --config java
this jdk_home.sh file kept overriding the $PATH on boot-up.
I think the best ranking is
1.node-schedule
2.later
3.crontab
and the sample of node-schedule is below:
var schedule = require("node-schedule");
var rule = new schedule.RecurrenceRule();
//rule.minute = 40;
rule.second = 10;
var jj = schedule.scheduleJob(rule, function(){
console.log("execute jj");
});
Maybe you can find the answer from node modules.
Use tar along with a pipe.
cd /source_directory
tar cf - --exclude=dir_to_exclude . | (cd /destination && tar xvf - )
You can even use this technique across ssh.
There are two ways to fix this:
1. Unix Way: In 4 simple steps
which git
in the terminal to know the location of your git
executable. Open that directory & locate gitk
inside the bin
folder. Copy the path --- typically /usr/local/git/bin
~/.bash_profile
to add the location of local git
& gitk
in the paths or, simply copy-pasta from the sample written below.Sample bash_profile
:
# enabling gitk
export PATH=/usr/local/git/bin:$PATH
If you don't have a bash_profile
want to learn how to create one, then click here.
gitk
executable (typically at /usr/local/bin/gitk
), take a backup & open it in a text editor. Find all occurences of lime
in the file & replace them with "#99FF00"
.source ~/.bash_profile
Now, run gitk
2. HomeBrew way
Updates - If you do not have homebrew
on your mac, get it installed first. It may require sudo
privileges.
brew update
brew doctor
brew link git
/usr/local/Cellar/git/2.4.0/bin
to path & then reload bash & run gitk
which git
& observe if git is still linked to /usr/bin/git
source ~/.bash_profile
Simply You need to pass resizeMode like this to fit in your image in containing view
<Image style={styles.imageStyle} resizeMode={'cover'} source={item.image}/>
const style = StyleSheet.create({
imageStyle: {
alignSelf: 'center',
height:'100%',
width:'100%'
},]
})
Herer's my solution:
/**
* Tests two data structures for equality
* @param {object} x
* @param {object} y
* @returns {boolean}
*/
var equal = function(x, y) {
if (typeof x !== typeof y) return false;
if (x instanceof Array && y instanceof Array && x.length !== y.length) return false;
if (typeof x === 'object') {
for (var p in x) if (x.hasOwnProperty(p)) {
if (typeof x[p] === 'function' && typeof y[p] === 'function') continue;
if (x[p] instanceof Array && y[p] instanceof Array && x[p].length !== y[p].length) return false;
if (typeof x[p] !== typeof y[p]) return false;
if (typeof x[p] === 'object' && typeof y[p] === 'object') { if (!equal(x[p], y[p])) return false; } else
if (x[p] !== y[p]) return false;
}
} else return x === y;
return true;
};
Works with any nested data structure, and obviously ignores objects' methods. Don't even think of extending Object.prototype with this method, when I tried this once, jQuery broke ;)
For most arrays it's still faster than most of serialization solutions. It's probably the fastest compare method for arrays of object records.
None of the above worked for me. And it took me long to figure it out, hopefully this helps the next guy.
I'm using Ubuntu 12.04 LTS with mailutils v2.1.
I found this solutions somewhere on the net, don't know where, can't find it again:
-aFrom:[email protected]
Full Command used:
cat /root/Reports/ServerName-Report-$DATE.txt | mail -s "Server-Name-Report-$DATE" [email protected] -aFrom:[email protected]
If you use Firebug, you can use console.log to output an object and get a hyperlinked, explorable item in the console.
In my case, where the timezones are not available on the server, this works great:
SELECT CONVERT_TZ(`date_field`,'+00:00',@@global.time_zone) FROM `table`
Note: global.time_zone uses the server timezone. You have to make sure, that it has the desired timezone!
I ran into this error using node 0.12.0
and it was fixed by deleting the existing /node_modules
directory and running npm update
.
This may be OT but if you are serializing a lot of primitive types or POD structures, Google Protocol Buffers for .Net might be useful to you. This addresses the endianness issue @Marc raised above, among other useful features.
A method for future reference is something like this. bannedphraseform is the first form and expectedphraseform is the second. If the first one is hit, the second one is skipped (which is a reasonable assumption in this case):
if request.method == 'POST':
bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
if bannedphraseform.is_valid():
bannedphraseform.save()
else:
bannedphraseform = BannedPhraseForm(prefix='banned')
if request.method == 'POST' and not bannedphraseform.is_valid():
expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
bannedphraseform = BannedPhraseForm(prefix='banned')
if expectedphraseform.is_valid():
expectedphraseform.save()
else:
expectedphraseform = ExpectedPhraseForm(prefix='expected')
A scriptless, CSS-only experimental approach with image pre-loadingBONUS! and which only works in Firefox:
<style>
a.zoom .full { display: none; }
a.zoom:active .thumb { display: none; }
a.zoom:active .full { display: inline; }
</style>
<a class="zoom" href="#">
<img class="thumb" src="thumbnail.png"/>
<img class="full" src="fullsize.png"/>
</a>
Shows the thumbnail by default. Shows the full size image while the mouse button is clicked and held down. Goes back to the thumbnail as soon as the button is released. I'm in no way suggesting that this method be used; it's just a demo of a CSS-only approach that [very] partially solves the problem. With some z-index + relative position tweaks, it could work in other browsers too.
Try dont shut down iptables and open port 3306.
sudo iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT
or sudo ufw allow 3306
if you use ufw.
check: netstat -lnp | grep mysql
you should get sth like that:
cp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 2048/mysqld
tcp6 0 0 :::33060 :::* LISTEN 2048/mysqld
unix 2 [ ACC ] STREAM LISTENING 514961 2048/mysqld /var/run/mysqld/mysqld.sock
unix 2 [ ACC ] STREAM LISTENING 514987 2048/mysqld /var/run/mysqld/mysqlx.sock
if you have null then delete # before port = 3306 in cnf file.
I had a further issue that foxed me for a while when theming existing code from a CMS. I wanted to use flexbox with justify-content:space-between
but the left and right elements weren't flush.
In that system the items were floated and the container had a :before
and/or an :after
to clear floats at beginning or end. So setting those sneaky :before
and :after
elements to display:none
did the trick.
first, you need to load URL helper like this type or you can upload within autoload.php file:
$this->load->helper('url');
if (!$user_logged_in)
{
redirect('/account/login', 'refresh');
}
I have tried the following config for eclipse.ini:
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
1024M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
1024m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms128m
-Xmx2048m
Now eclipse performance is about 2 times faster then before.
You can also find a good help ref here: http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html
One option is that you could use system()
to execute cp
. This just re-uses the cp(1)
command to do the work. If you only need to make another link to the file, this can be done with link()
or symlink()
.
There a small difference when u use rgba(255,255,255,a),background color becomes more and more lighter as the value of 'a' increase from 0.0 to 1.0. Where as when use rgba(0,0,0,a), the background color becomes more and more darker as the value of 'a' increases from 0.0 to 1.0. Having said that, its clear that both (255,255,255,0) and (0,0,0,0) make background transparent. (255,255,255,1) would make the background completely white where as (0,0,0,1) would make background completely black.
I made an eol
module for working with line endings in node or browsers. It has a split method like
var lines = eol.split(text)
Check out Abraxas Code Check http://www.abxsoft.com/codchk_user.html
Use this code to ensure the user doesn't just enter spaces but a valid name:
pattern="[a-zA-Z][a-zA-Z0-9\s]*"
Q1.) Assuming process B tries to take ownership of the same mutex you locked in process A (you left that out of your pseudocode) then no, process B cannot access sharedResource while the mutex is locked since it will sit waiting to lock the mutex until it is released by process A. It will return from the mutex_lock() function when the mutex is locked (or when an error occurs!)
Q2.) In Process B, ensure you always lock the mutex, access the shared resource, and then unlock the mutex. Also, check the return code from the mutex_lock( pMutex ) routine to ensure that you actually own the mutex, and ONLY unlock the mutex if you have locked it. Do the same from process A.
Both processes should basically do the same thing when accessing the mutex.
lock()
If the lock succeeds, then {
access sharedResource
unlock()
}
Q3.) Yes, there are lots of diagrams: =) https://www.google.se/search?q=mutex+thread+process&rlz=1C1AFAB_enSE487SE487&um=1&ie=UTF-8&hl=en&tbm=isch&source=og&sa=N&tab=wi&ei=ErodUcSmKqf54QS6nYDoAw&biw=1200&bih=1730&sei=FbodUbPbB6mF4ATarIBQ
It looks like you were on the right track - get_FOO_display()
is most certainly what you want:
In templates, you don't include ()
in the name of a method. Do the following:
{{ person.get_gender_display }}
Please don't try and roll your own with a TreeView/DirectoryInfo class. For one thing there are many nice features you get for free (icons/right-click/networks) by using SHBrowseForFolder. For another there are a edge cases/catches you will likely not be aware of.
You can try:
df[0] = df[0].str.strip()
or more specifically for all string columns
non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())
you have to split the datetime and then store it with your desired format like dd/MM/yyyy. then you can use this query with between but i have objection using this becasue it will search every single data on your database,so i suggest you can use datediff.
Dim start = txtstartdate.Text.Trim()
Dim endday = txtenddate.Text.Trim()
Dim arr()
arr = Split(start, "/")
Dim dt As New DateTime
dt = New Date(Val(arr(2).ToString), Val(arr(1).ToString), Val(arr(0).ToString))
Dim arry()
arry = Split(endday, "/")
Dim dt2 As New DateTime
dt2 = New Date(Val(arry(2).ToString), Val(arry(1).ToString), Val(arry(0).ToString))
qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "
here i have used dd/MM/yyyy format.
As of Json.NET 4.0 Release 1, there is native dynamic support.
You don't need to declare a class, just use dynamic
:
dynamic jsonDe = JsonConvert.DeserializeObject(json);
All the fields will be available:
foreach (string typeStr in jsonDe.Type[0])
{
// Do something with typeStr
}
string t = jsonDe.t;
bool a = jsonDe.a;
object[] data = jsonDe.data;
string[][] type = jsonDe.Type;
With dynamic you don't need to create a specific class to hold your data.
The other answers to this question seem to hit it spot on. Now how would you figure this out for yourself without stack overflow? Check out IPython, an interactive Python shell that has tab auto-complete.
> ipython
import Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
Type "copyright", "credits" or "license" for more information.
IPython 0.8.2.svn.r2750 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import datetime
In [2]: now=datetime.datetime.now()
In [3]: now.
press tab a few times and you'll be prompted with the members of the "now" object:
now.__add__ now.__gt__ now.__radd__ now.__sub__ now.fromordinal now.microsecond now.second now.toordinal now.weekday
now.__class__ now.__hash__ now.__reduce__ now.astimezone now.fromtimestamp now.min now.strftime now.tzinfo now.year
now.__delattr__ now.__init__ now.__reduce_ex__ now.combine now.hour now.minute now.strptime now.tzname
now.__doc__ now.__le__ now.__repr__ now.ctime now.isocalendar now.month now.time now.utcfromtimestamp
now.__eq__ now.__lt__ now.__rsub__ now.date now.isoformat now.now now.timetuple now.utcnow
now.__ge__ now.__ne__ now.__setattr__ now.day now.isoweekday now.replace now.timetz now.utcoffset
now.__getattribute__ now.__new__ now.__str__ now.dst now.max now.resolution now.today now.utctimetuple
and you'll see that now.year is a member of the "now" object.
Ok, for @AndrewS solution to work with v7 appCompat library:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:someNamespace="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/saved_badge"
someNamespace:showAsAction="always"
android:icon="@drawable/shape_notification" />
</menu>
.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.saved_badge);
MenuItemCompat.setActionView(item, R.layout.feed_update_count);
View view = MenuItemCompat.getActionView(item);
notifCount = (Button)view.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
}
private void setNotifCount(int count){
mNotifCount = count;
supportInvalidateOptionsMenu();
}
The rest of the code is the same.
In case you want an awk-only solution without creating a temporary file and usable with version!=(gawk 4.1.0):
awk '{a[b++]=$0} END {for(c=0;c<=b;c++)print a[c]>ARGV[1]}' file
If it's not the Home edition of XP, you can use \\servername\c$
Mark Brackett's comment:
Note that you need to be an Administrator on the local machine, as the share permissions are locked down
I know this is an old post, but for anyone upgrading to Mountain Lion (10.8) and experiencing similar issues, adding FollowSymLinks
to your {username}.conf file (in /etc/apache2/users/) did the trick for me. So the file looks like this:
<Directory "/Users/username/Sites/">
Options Indexes MultiViews FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
River is a good solution once you want to have a almost real time synchronization and general solution.
If you have data in MongoDB already and want to ship it very easily to Elasticsearch like "one-shot" you can try my package in Node.js https://github.com/itemsapi/elasticbulk.
It's using Node.js streams so you can import data from everything what is supporting streams (i.e. MongoDB, PostgreSQL, MySQL, JSON files, etc)
Example for MongoDB to Elasticsearch:
Install packages:
npm install elasticbulk
npm install mongoose
npm install bluebird
Create script i.e. script.js:
const elasticbulk = require('elasticbulk');
const mongoose = require('mongoose');
const Promise = require('bluebird');
mongoose.connect('mongodb://localhost/your_database_name', {
useMongoClient: true
});
mongoose.Promise = Promise;
var Page = mongoose.model('Page', new mongoose.Schema({
title: String,
categories: Array
}), 'your_collection_name');
// stream query
var stream = Page.find({
}, {title: 1, _id: 0, categories: 1}).limit(1500000).skip(0).batchSize(500).stream();
elasticbulk.import(stream, {
index: 'my_index_name',
type: 'my_type_name',
host: 'localhost:9200',
})
.then(function(res) {
console.log('Importing finished');
})
Ship your data:
node script.js
It's not extremely fast but it's working for millions of records (thanks to streams).
Just run composer install
- it will make your vendor
directory reflect dependencies in composer.lock
file.
In other words - it will delete any vendor which is missing in composer.lock
.
Please update the composer itself before running this.
For Print Result to text file
we can follow
echo "test data" > test.txt
This will create test.txt file and written "test data"
If you want to append then
echo "test data" >> test.txt
I'm using this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUrl);
System.Diagnostics.Stopwatch timer = new Stopwatch();
timer.Start();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode.ToString();
response.Close();
timer.Stop();
You can change this in the page load
.
My intention is that when the page comes to the load
function, switch the links (the current link in the required one)
This happened to me today after my Macbook's battery died. I think this can be caused by improper shutdown. All you have to do in cases such as mine is delete postmaster.pid
Navigate to the folder
cd /usr/local/var/postgres
Check to see if postmaster.pid is present
ls
Remove postmaster.pid
rm postmaster.pid
If you also have jQuery UI, you can add this:
$(document).ready(function () {
$(document).tooltip();
});
You then need a title instead of a hidden input. RGraham already posted an answer doing this for you :P
Some handy quick functions (if you're not using Boost):
template<typename T>
std::string ToString(const T& v)
{
std::ostringstream ss;
ss << v;
return ss.str();
}
template<typename T>
T FromString(const std::string& str)
{
std::istringstream ss(str);
T ret;
ss >> ret;
return ret;
}
Example:
int i = FromString<int>(s);
std::string str = ToString(i);
Works for any streamable types (floats etc). You'll need to #include <sstream>
and possibly also #include <string>
.
Annotations are meta-meta-objects which can be used to describe other meta-objects. Meta-objects are classes, fields and methods. Asking an object for its meta-object (e.g. anObj.getClass()
) is called introspection. The introspection can go further and we can ask a meta-object what are its annotations (e.g. aClass.getAnnotations
). Introspection and annotations belong to what is called reflection and meta-programming.
An annotation needs to be interpreted in one way or another to be useful. Annotations can be interpreted at development-time by the IDE or the compiler, or at run-time by a framework.
Annotation processing is a very powerful mechanism and can be used in a lot of different ways:
@Deprecated, @Override
, or @NotNull
@Entity, @TestCase, @WebService
@Statefull, @Transaction
@Column, @XmlElement
In all cases, an annotation is used to describe the element and clarify its meaning.
Prior to JDK5, information that is now expressed with annotations needed to be stored somewhere else, and XML files were frequently used. But it is more convenient to use annotations because they will belong to the Java code itself, and are hence much easier to manipulate than XML.
Usage of annotations:
...have a look for instance at the project Lombok, which uses annotations to define how to generate equals
or hashCode
methods.
I thought I'd add my approach, in the context of a practical example. I use a similar check when dealing with values going in and coming out of Memjs, so even though the value saved may be string, array or object, Memjs expects a string. The function first checks if a key/value pair already exists, if it does then a precheck is done to determine if value needs to be parsed before being returned:
function checkMem(memStr) {
let first = memStr.slice(0, 1)
if (first === '[' || first === '{') return JSON.parse(memStr)
else return memStr
}
Otherwise, the callback function is invoked to create the value, then a check is done on the result to see if the value needs to be stringified before going into Memjs, then the result from the callback is returned.
async function getVal() {
let result = await o.cb(o.params)
setMem(result)
return result
function setMem(result) {
if (typeof result !== 'string') {
let value = JSON.stringify(result)
setValue(key, value)
}
else setValue(key, result)
}
}
The complete code is below. Of course this approach assumes that the arrays/objects going in and coming out are properly formatted (i.e. something like "{ key: 'testkey']" would never happen, because all the proper validations are done before the key/value pairs ever reach this function). And also that you are only inputting strings into memjs and not integers or other non object/arrays-types.
async function getMem(o) {
let resp
let key = JSON.stringify(o.key)
let memStr = await getValue(key)
if (!memStr) resp = await getVal()
else resp = checkMem(memStr)
return resp
function checkMem(memStr) {
let first = memStr.slice(0, 1)
if (first === '[' || first === '{') return JSON.parse(memStr)
else return memStr
}
async function getVal() {
let result = await o.cb(o.params)
setMem(result)
return result
function setMem(result) {
if (typeof result !== 'string') {
let value = JSON.stringify(result)
setValue(key, value)
}
else setValue(key, result)
}
}
}
There are various ways to get a Set
as:
List<Integer> sourceList = new ArrayList();
sourceList.add(1);
sourceList.add(2);
sourceList.add(3);
sourceList.add(4);
// Using Core Java
Set<Integer> set1 = new HashSet<>(sourceList); //needs null-check if sourceList can be null.
// Java 8
Set<Integer> set2 = sourceList.stream().collect(Collectors.toSet());
Set<Integer> set3 = sourceList.stream().collect(Collectors.toCollection(HashSet::new));
//Guava
Set<Integer> set4 = Sets.newHashSet(sourceList);
// Apache commons
Set<Integer> set5 = new HashSet<>(4);
CollectionUtils.addAll(set5, sourceList);
When we use Collectors.toSet()
it returns a set and as per the doc:There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned
. If we want to get a HashSet
then we can use the other alternative to get a set (check set3
).
Bootstrap 4 has two dependencies: jQuery 1.9.1 and popper.js 1.12.3. When you install Bootstrap 4, you need to install these two dependencies.
npm install popper.js@^1.12.3 --save
npm install [email protected] --save
npm install [email protected] --save
For Bootstrap 4.1
npm install popper.js@^1.14.3 --save
npm install [email protected] --save
npm install [email protected] --save
The CosisEntities
class is your DbContext
. When you create a context in a using
block, you're defining the boundaries for your data-oriented operation.
In your code, you're trying to emit the result of a query from a method and then end the context within the method. The operation you pass the result to then tries to access the entities in order to populate the grid view. Somewhere in the process of binding to the grid, a lazy-loaded property is being accessed and Entity Framework is trying to perform a lookup to obtain the values. It fails, because the associated context has already ended.
You have two problems:
You're lazy-loading entities when you bind to the grid. This means that you're doing lots of separate query operations to SQL Server, which are going to slow everything down. You can fix this issue by either making the related properties eager-loaded by default, or asking Entity Framework to include them in the results of this query by using the Include
extension method.
You're ending your context prematurely: a DbContext
should be available throughout the unit of work being performed, only disposing it when you're done with the work at hand. In the case of ASP.NET, a unit of work is typically the HTTP request being handled.
In my case, I just put the aar file in libs, and add
dependencies {
...
api fileTree(dir: 'libs', include: ['*.aar'])
...
}
in build.gradle and it works. I think it is similar with default generated dependency:
implementation fileTree(dir: 'libs', include: ['*.jar'])
I suggest using Hits's answer, but adding a Locale format, this is how Android Developers recommends:
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
return dateFormat.format(new Date()); // Find todays date
} catch (Exception e) {
e.printStackTrace();
return null;
}
Use animation-fill-mode: forwards;
animation-fill-mode: forwards;
The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count).
Note: The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.
Working example
div {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: red;_x000D_
position :relative;_x000D_
-webkit-animation: mymove 3ss forwards; /* Safari 4.0 - 8.0 */_x000D_
animation: bubble 3s forwards;_x000D_
/* animation-name: bubble; _x000D_
animation-duration: 3s;_x000D_
animation-fill-mode: forwards; */_x000D_
}_x000D_
_x000D_
/* Safari */_x000D_
@-webkit-keyframes bubble {_x000D_
0% { transform:scale(0.5); opacity:0.0; left:0}_x000D_
50% { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}_x000D_
_x000D_
/* Standard syntax */_x000D_
@keyframes bubble {_x000D_
0% { transform:scale(0.5); opacity:0.0; left:0}_x000D_
50% { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}
_x000D_
<h1>The keyframes </h1>_x000D_
<div></div>
_x000D_
Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.
Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).
function append_output(suffix, value) {
$("#output_"+suffix).append(value)
}
function kickOff() {
let start = new Promise((resolve, reject) => {
append_output("now", "start")
resolve("start")
})
let middle = new Promise((resolve, reject) => {
setTimeout(() => {
append_output("now", " middle")
resolve(" middle")
}, 1000)
})
let end = new Promise((resolve, reject) => {
append_output("now", " end")
resolve(" end")
})
Promise.all([start, middle, end]).then(results => {
results.forEach(
result => append_output("later", result))
})
}
kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
Well I always use the same easy way and it works for me. In your HTML keep the type as text (like this):
<input type="text" class="textfield" value="" id="onlyNumbers" name="onlyNumbers" onkeypress="return isNumber(event)" onpaste="return false;"/>
After this you only need to add a method on javascript
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ( (charCode > 31 && charCode < 48) || charCode > 57) {
return false;
}
return true;
}
</script>
With this easy validation you will only get positive numbers as you wanted. You can modify the charCodes to add more valid keys to your method.
Here´s the code working: Only numbers validation
If you deal with .xlsm
file instead of .xls
you can use the old method. I was trying to modify vbaProject.bin
in .xlsm
several times using DBP->DBx
method by it didn't work, also changing value of DBP
didn't. So I was very suprised that following worked :
1. Save .xlsm
as .xls
.
2. Use DBP->DBx
method on .xls
.
3. Unfortunately some erros may occur when using modified .xls
file, I had to save .xls
as .xlsx
and add modules, then save as .xlsm
.
Probably the shortest version:
[System.Collections.ArrayList]$someArray
It is also faster because it does not call relatively expensive New-Object
.
Maybe my response quite late, but it covers API below and above 21 level.
To add headers we should intercept every request and create new one with required headers.
So we need to override shouldInterceptRequest method called in both cases: 1. for API until level 21; 2. for API level 21+
webView.setWebViewClient(new WebViewClient() {
// Handle API until level 21
@SuppressWarnings("deprecation")
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return getNewResponse(url);
}
// Handle API 21+
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
return getNewResponse(url);
}
private WebResourceResponse getNewResponse(String url) {
try {
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url.trim())
.addHeader("Authorization", "YOU_AUTH_KEY") // Example header
.addHeader("api-key", "YOUR_API_KEY") // Example header
.build();
Response response = httpClient.newCall(request).execute();
return new WebResourceResponse(
null,
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
} catch (Exception e) {
return null;
}
}
});
If response type should be processed you could change
return new WebResourceResponse(
null, // <- Change here
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
to
return new WebResourceResponse(
getMimeType(url), // <- Change here
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
and add method
private String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
switch (extension) {
case "js":
return "text/javascript";
case "woff":
return "application/font-woff";
case "woff2":
return "application/font-woff2";
case "ttf":
return "application/x-font-ttf";
case "eot":
return "application/vnd.ms-fontobject";
case "svg":
return "image/svg+xml";
}
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
Year back i also faced same problem on mysql5.7 version and ibdata1 occupied 150 Gb. so i added undo tablespaces
Take Mysqldump backup
Stop mysql service
Remove all data from data dir
Add below undo tablespace parameter in current my.cnf
#undo tablespace
innodb_undo_directory = /var/lib/mysql/
innodb_rollback_segments = 128
innodb_undo_tablespaces = 3
innodb_undo_logs = 128
innodb_max_undo_log_size=1G
innodb_undo_log_truncate = ON
Start mysql service
store mysqldump backup
Problem resolved !!
You can do this to only monitor own properties of the object:
var arr = [];
for (var key in p) {
if (p.hasOwnProperty(key)) {
arr.push(p[key]);
}
}
The best approach for you to communicate between the two controllers is to use events.
See the scope documentation
In this check out $on
, $broadcast
and $emit
.
A three line solution, but works quite well:
int[] source_array = {0,1,2,3,4,5,6,7,8,9,10,11};
ArrayList<Integer> target_list = new ArrayList<Integer>();
for(int i = 0; i < source_array.length; i++){
target_list.add(random_array[i]);
}
replace:true
is DeprecatedFrom the Docs:
replace
([DEPRECATED!], will be removed in next major release - i.e. v2.0)specify what the template should replace. Defaults to
false
.
true
- the template will replace the directive's element.false
- the template will replace the contents of the directive's element.
-- AngularJS Comprehensive Directive API
From GitHub:
Caitp-- It's deprecated because there are known, very silly problems with
replace: true
, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".
Note:
replace: true
is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.
transclude: element
in the replace template root can have unexpected effectsFor more information, see
While the accepted answer is very true, just want to point out that AllowTransparency has some downfalls. It does not allow child window controls to show up, ie WebBrowser, and it usually forces software rendering which can have negative performance effects.
There is a better work around though.
When you want to create a window with no border that is resizeable and is able to host a WebBrowser control or a Frame control pointed to a URL you simply couldn't, the contents of said control would show empty.
I found a workaround though; in the Window, if you set the WindowStyle to None, ResizeMode to NoResize (bear with me, you will still be able to resize once done) then make sure you have UNCHECKED AllowsTransparency you will have a static sized window with no border and will show the browser control.
Now, you probably still want to be able to resize right? Well we can to that with a interop call:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
//Attach this to the MouseDown event of your drag control to move the window in place of the title bar
private void WindowDrag(object sender, MouseButtonEventArgs e) // MouseDown
{
ReleaseCapture();
SendMessage(new WindowInteropHelper(this).Handle,
0xA1, (IntPtr)0x2, (IntPtr)0);
}
//Attach this to the PreviewMousLeftButtonDown event of the grip control in the lower right corner of the form to resize the window
private void WindowResize(object sender, MouseButtonEventArgs e) //PreviewMousLeftButtonDown
{
HwndSource hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
SendMessage(hwndSource.Handle, 0x112, (IntPtr)61448, IntPtr.Zero);
}
And voila, A WPF window with no border and still movable and resizable without losing compatibility with with controls like WebBrowser
You can't do it with "anonymous" type parameters (ie, wildcards that use ?
), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.
import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
T t;
}
Most of the aspects are covered. But there could be a requirement to find the aggregation of other data types apart from Integer, Long(for which specialized stream support is already present). For e.g. stram with BigInteger For such a type we can use reduce operation like
list.stream().reduce((bigInteger1, bigInteger2) -> bigInteger1.add(bigInteger2))
System: Ubuntu 16.04 LTS, yet you can try these steps in accordance to your respective systems.
If there is an SDK file present, it should be most likely found at /home/USERNAME/Android/sdk
USERNAME
is to be replaced by your username
If there is none, check the specified sdk path for the project in android studio.
File > Project Structure > sdk path
The sdk directory should be present in the specified path. In case, it is not there, open the file:
PROJECT_DIRECTORY/android/local.properties
PROJECT_DIRECTORY
needs to be replaced by your project name.
If the file is not there, create it. Then add the following line depending on where you find the sdk directory.
If sdk is there at /home/USERNAME/Android/
:
add the line: sdk.dir = /home/tanya/Android/sdk
If sdk is not there at /home/USERNAME/Android/
:
add the line: sdk.dir = /home/tanya/Android/
If the path specified for sdk directory in 'Project Structure' is entirely different and the sdk directory is present at the specified location,
add the line: sdk.dir = SPECIFIED_SDK_PATH
Add the specified sdk path in place of SPECIFIED_SDK_PATH
from Object import Object
or
From Class_Name import Class_name
If Object is a .py
file.
function strip_html_tags(str)
{
if ((str===null) || (str===''))
return false;
else
str = str.toString();
return str.replace(/<[^>]*>/g, '');
}
I understand this is a very old thread. However, wanted to share how I encountered the message in my scenario and in case it might help others
Add-Migration <Migration_name>
on my local machine. Didn't run the update-database
yet.update-database
.enable-migrations -force
in my application. Rather my preferred way is execute the update-database -script
command to control the target migrations I need.My solution was to run update-database -Script -TargetMigration <migration_name_from_merge>
and then my update-database -Script -TargetMigration <migration_name>
which generated 2 scripts that I was able to run manually on my local db.
Needless to say above experience is on my local machine.
I can't stress this advice enough: use a reset stylesheet, then set everything explicitly. It'll cut your cross-browser CSS development time in half.
Try Eric Meyer's reset.css.
simply do the select
:
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))
Reinstalling the nuget solved it for me
PM> Install-Package Microsoft.AspNet.Razor -Version 3.2.3
Normally, I'd suggest trying the ANSI-92 standard meta tables for something like this but I see now that Oracle doesn't support it.
-- this works against most any other database
SELECT
*
FROM
INFORMATION_SCHEMA.COLUMNS C
INNER JOIN
INFORMATION_SCHEMA.TABLES T
ON T.TABLE_NAME = C.TABLE_NAME
WHERE
C.COLUMN_NAME = 'columnname'
AND T.TABLE_NAME = 'tablename'
Instead, it looks like you need to do something like
-- Oracle specific table/column query
SELECT
*
FROM
ALL_TAB_COLUMNS
WHERE
TABLE_NAME = 'tablename'
AND COLUMN_NAME = 'columnname'
I do apologize in that I don't have an Oracle instance to verify the above. If it does not work, please let me know and I will delete this post.
Basic Generic Question - Simplest Generic Answer ;)
Given the information I will make the assumption that you might be trying a basic approach to coding, building/compiling and running a simple console app like "Hello World", using some simple text editor and some Command Shell.
This error occurs in the fallowing scenario:
..\SomePath>javac HelloWorld.java
..\SomePath>java HelloWorld.class
In other words, use:
..\SomePath>java HelloWorld
P.S. The adding the file extension .class produces the same mistake. Also be sure to have the Java's (JDK/JRE) bin folder in the operating system's Environment Variables's PATH.(Lookup for more details other posts on this) P.P.S Was I correct in my assumption/s?
SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || "tag_name" || '%';
tag_name
should be in quotation otherwise it will give error as tag_name doest not exist
You could also use:
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
I believe you could try something like this:
var postData =
{
"bid":bid,
"location1":"1","quantity1":qty1,"price1":price1,
"location2":"2","quantity2":qty2,"price2":price2,
"location3":"3","quantity3":qty3,"price3":price3
}
$.ajax({
type: "POST",
dataType: "json",
url: "add_cart.php",
data: postData,
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
the json encode should happen automatically, and a dump of your post should give you something like:
array(
"bid"=>bid,
"location1"=>"1",
"quantity1"=>qty1,
"price1"=>price1,
"location2"=>"2",
"quantity2"=>qty2,
"price2"=>price2,
"location3"=>"3",
"quantity3"=>qty3,
"price3"=>price3
)
Extending Magpie's answer, here is the code for action filter which I use in my project.
It works with ASP Core RC2!
public class ReCaptchaAttribute : ActionFilterAttribute
{
private readonly string CAPTCHA_URL = "https://www.google.com/recaptcha/api/siteverify";
private readonly string SECRET = "your_secret";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
// Get recaptcha value
var captchaResponse = filterContext.HttpContext.Request.Form["g-recaptcha-response"];
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "secret", SECRET },
{ "response", captchaResponse },
{ "remoteip", filterContext.HttpContext.Request.HttpContext.Connection.RemoteIpAddress.ToString() }
};
var content = new FormUrlEncodedContent(values);
var result = client.PostAsync(CAPTCHA_URL, content).Result;
if (result.IsSuccessStatusCode)
{
string responseString = result.Content.ReadAsStringAsync().Result;
var captchaResult = JsonConvert.DeserializeObject<CaptchaResponseViewModel>(responseString);
if (!captchaResult.Success)
{
((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Captcha not solved");
}
} else
{
((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Captcha error");
}
}
}
catch (System.Exception)
{
((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Unknown error");
}
}
}
And use it in your code like
[ReCaptcha]
public IActionResult Authenticate()
{
if (!ModelState.IsValid)
{
return View(
"Login",
new ReturnUrlViewModel
{
ReturnUrl = Request.Query["returnurl"],
IsError = true,
Error = "Wrong reCAPTCHA"
}
);
}
Going with what you've started:
row = [[]]
crimefile = open(fileName, 'r')
for line in crimefile.readlines():
tmp = []
for element in line[0:-1].split(','):
tmp.append(element)
row.append(tmp)
Sure, convert the file to ascii and blast all unicode characters away. It will probably work.... BUT...
Two more sugrical approaches to fixing the problem:
Regex search all unicode characters not part non-extended ascii. In notepad++ I can search up to FFFF, which hasn't failed me yet.
[\x{80}-\x{FFFF}]
80 is hex for 128, the first extended ascii character.
After hitting "find next" and highlighting what appears to be empty space, you can close your search dialog and press CTRL+C to copy to clipboard.
Then paste the character into a unicode search tool. I usually use an online one. http://unicode.scarfboy.com/
Example: I had a bullet point (•) in my code somehow. The unicode value is 2022 (hex), but when read as ascii by the compiler you get \342 \200 \242 (3 octal values). It's not as simple as converting each octal values to hex and smashing them together. So "E2 80 A2" is NOT the hex unicode point in your code.
SELECT column_name,data_type
FROM information_schema.columns
WHERE
table_name = 'your_table_name'
AND table_catalog = 'your_database_name'
AND table_schema = 'your_schema_name';
Use case match for early return purpose. It will force you to declare all return branches explicitly, preventing the careless mistake of forgetting to write return somewhere.
For Windows Use this class
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}
How about Excel Data Reader?
http://exceldatareader.codeplex.com/
I've used in it anger, in a production environment, to pull large amounts of data from a variety of Excel files into SQL Server Compact. It works very well and it's rather robust.
For Python 3 you could try using quote
instead of quote_plus
:
import urllib.parse
print(urllib.parse.quote("http://www.sample.com/"))
Result:
http%3A%2F%2Fwww.sample.com%2F
Or:
from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")
Result:
'https://www.sample.com/?id=123%20abc'
None of the above solutions were suitable for my scenario, handling .Navigated and .FileDownload events seemed like a good fit but accessing the WebBrowser.Document property threw an UnauthorizedAccessException which is caused by cross frame scripting security (our web content contains frames - all on the same domain/address but frames have their own security holes that are being blocked).
The solution that worked was to override IOleCommandTarget and to catch the script error commands at that level. Here's the WebBrowser sub-class to achieve this:
/// <summary>
/// Subclassed WebBrowser that suppresses error pop-ups.
///
/// Notes.
/// ScriptErrorsSuppressed property is not used because this actually suppresses *all* pop-ups.
///
/// More info at:
/// http://stackoverflow.com/questions/2476360/disable-javascript-error-in-webbrowser-control
/// </summary>
public class WebBrowserEx : WebBrowser
{
#region Constructor
/// <summary>
/// Default constructor.
/// Initialise browser control and attach customer event handlers.
/// </summary>
public WebBrowserEx()
{
this.ScriptErrorsSuppressed = false;
}
#endregion
#region Overrides
/// <summary>
/// Override to allow custom script error handling.
/// </summary>
/// <returns></returns>
protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
{
return new WebBrowserSiteEx(this);
}
#endregion
#region Inner Class [WebBrowserSiteEx]
/// <summary>
/// Sub-class to allow custom script error handling.
/// </summary>
protected class WebBrowserSiteEx : WebBrowserSite, NativeMethods.IOleCommandTarget
{
/// <summary>
/// Default constructor.
/// </summary>
public WebBrowserSiteEx(WebBrowserEx webBrowser) : base (webBrowser)
{
}
/// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
/// <param name="prgCmds">An array of OLECMD structures that indicate the commands for which the caller needs status information. This method fills the <paramref name="cmdf" /> member of each structure with values taken from the OLECMDF enumeration.</param>
/// <param name="pCmdText">An OLECMDTEXT structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
/// <returns>This method returns S_OK on success. Other possible return values include the following.
/// E_FAIL The operation failed.
/// E_UNEXPECTED An unexpected error has occurred.
/// E_POINTER The <paramref name="prgCmds" /> argument is null.
/// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
public int QueryStatus(ref Guid pguidCmdGroup, int cCmds, NativeMethods.OLECMD prgCmds, IntPtr pCmdText)
{
if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == prgCmds.cmdID)
{ // Do nothing (suppress script errors)
return NativeMethods.S_OK;
}
// Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
}
/// <summary>Executes the specified command.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="nCmdID">The command ID.</param>
/// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
/// <param name="pvaIn">The input arguments of the command.</param>
/// <param name="pvaOut">The output arguments of the command.</param>
/// <returns>This method returns S_OK on success. Other possible return values include
/// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
/// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
/// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
/// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
/// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
public int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, object[] pvaIn, int pvaOut)
{
if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == nCmdID)
{ // Do nothing (suppress script errors)
return NativeMethods.S_OK;
}
// Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
}
}
#endregion
}
~
/// <summary>
/// Native (unmanaged) methods, required for custom command handling for the WebBrowser control.
/// </summary>
public static class NativeMethods
{
/// From docobj.h
public const int OLECMDERR_E_UNKNOWNGROUP = -2147221244;
/// <summary>
/// From Microsoft.VisualStudio.OLE.Interop (Visual Studio 2010 SDK).
/// </summary>
public enum OLECMDID
{
/// <summary />
OLECMDID_OPEN = 1,
/// <summary />
OLECMDID_NEW,
/// <summary />
OLECMDID_SAVE,
/// <summary />
OLECMDID_SAVEAS,
/// <summary />
OLECMDID_SAVECOPYAS,
/// <summary />
OLECMDID_PRINT,
/// <summary />
OLECMDID_PRINTPREVIEW,
/// <summary />
OLECMDID_PAGESETUP,
/// <summary />
OLECMDID_SPELL,
/// <summary />
OLECMDID_PROPERTIES,
/// <summary />
OLECMDID_CUT,
/// <summary />
OLECMDID_COPY,
/// <summary />
OLECMDID_PASTE,
/// <summary />
OLECMDID_PASTESPECIAL,
/// <summary />
OLECMDID_UNDO,
/// <summary />
OLECMDID_REDO,
/// <summary />
OLECMDID_SELECTALL,
/// <summary />
OLECMDID_CLEARSELECTION,
/// <summary />
OLECMDID_ZOOM,
/// <summary />
OLECMDID_GETZOOMRANGE,
/// <summary />
OLECMDID_UPDATECOMMANDS,
/// <summary />
OLECMDID_REFRESH,
/// <summary />
OLECMDID_STOP,
/// <summary />
OLECMDID_HIDETOOLBARS,
/// <summary />
OLECMDID_SETPROGRESSMAX,
/// <summary />
OLECMDID_SETPROGRESSPOS,
/// <summary />
OLECMDID_SETPROGRESSTEXT,
/// <summary />
OLECMDID_SETTITLE,
/// <summary />
OLECMDID_SETDOWNLOADSTATE,
/// <summary />
OLECMDID_STOPDOWNLOAD,
/// <summary />
OLECMDID_ONTOOLBARACTIVATED,
/// <summary />
OLECMDID_FIND,
/// <summary />
OLECMDID_DELETE,
/// <summary />
OLECMDID_HTTPEQUIV,
/// <summary />
OLECMDID_HTTPEQUIV_DONE,
/// <summary />
OLECMDID_ENABLE_INTERACTION,
/// <summary />
OLECMDID_ONUNLOAD,
/// <summary />
OLECMDID_PROPERTYBAG2,
/// <summary />
OLECMDID_PREREFRESH,
/// <summary />
OLECMDID_SHOWSCRIPTERROR,
/// <summary />
OLECMDID_SHOWMESSAGE,
/// <summary />
OLECMDID_SHOWFIND,
/// <summary />
OLECMDID_SHOWPAGESETUP,
/// <summary />
OLECMDID_SHOWPRINT,
/// <summary />
OLECMDID_CLOSE,
/// <summary />
OLECMDID_ALLOWUILESSSAVEAS,
/// <summary />
OLECMDID_DONTDOWNLOADCSS,
/// <summary />
OLECMDID_UPDATEPAGESTATUS,
/// <summary />
OLECMDID_PRINT2,
/// <summary />
OLECMDID_PRINTPREVIEW2,
/// <summary />
OLECMDID_SETPRINTTEMPLATE,
/// <summary />
OLECMDID_GETPRINTTEMPLATE
}
/// <summary>
/// From Microsoft.VisualStudio.Shell (Visual Studio 2010 SDK).
/// </summary>
public const int S_OK = 0;
/// <summary>
/// OLE command structure.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class OLECMD
{
/// <summary>
/// Command ID.
/// </summary>
[MarshalAs(UnmanagedType.U4)]
public int cmdID;
/// <summary>
/// Flags associated with cmdID.
/// </summary>
[MarshalAs(UnmanagedType.U4)]
public int cmdf;
}
/// <summary>
/// Enables the dispatching of commands between objects and containers.
/// </summary>
[ComVisible(true), Guid("B722BCCB-4E68-101B-A2BC-00AA00404770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IOleCommandTarget
{
/// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
/// <param name="prgCmds">An array of <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMD" /> structures that indicate the commands for which the caller needs status information.</param>
/// <param name="pCmdText">An <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT" /> structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
/// <returns>This method returns S_OK on success. Other possible return values include the following.
/// E_FAIL The operation failed.
/// E_UNEXPECTED An unexpected error has occurred.
/// E_POINTER The <paramref name="prgCmds" /> argument is null.
/// OLECMDERR_E_UNKNOWNGROUPThe <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
[PreserveSig]
[return: MarshalAs(UnmanagedType.I4)]
int QueryStatus(ref Guid pguidCmdGroup, int cCmds, [In] [Out] NativeMethods.OLECMD prgCmds, [In] [Out] IntPtr pCmdText);
/// <summary>Executes the specified command.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="nCmdID">The command ID.</param>
/// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
/// <param name="pvaIn">The input arguments of the command.</param>
/// <param name="pvaOut">The output arguments of the command.</param>
/// <returns>This method returns S_OK on success. Other possible return values include
/// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
/// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
/// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
/// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
/// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
[PreserveSig]
[return: MarshalAs(UnmanagedType.I4)]
int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, [MarshalAs(UnmanagedType.LPArray)] [In] object[] pvaIn, int pvaOut);
}
}
If you're in local machine then use this command
/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
For remote machine, use below one
/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
First reset.css
is the worst library you can use, because it removes the standard structure of HTML and displays everything you write just as text, after assigning the values of margin padding and other attributes to 0
. So for example you will find that <H1>
, will be the same as <H6>
.
On the other hand Normalize.css
uses the standard structure and also fixes almost all the errors existing in it. For example it fixes the problem with showing a form from one browser to another. Normalize fixes this by modifying this features so your elements will be shown the same on all browsers.
There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.
You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.
Here's a list of things that are worth checking:
Is Suhosin installed?
ini_set
ini_set('memory_limit', '512'); // DIDN'T WORK
ini_set('memory_limit', '512MB'); // DIDN'T WORK
ini_set('memory_limit', '512M'); // OK - 512MB
ini_set('memory_limit', 512000000); // OK - 512MB
When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
http://php.net/manual/en/ini.core.php#ini.memory-limit
Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or ini_set(). To clear a previously set value use none as the value.
public boolean checkInternetConnection()
{
boolean status = false;
Socket sock = new Socket();
InetSocketAddress address = new InetSocketAddress("www.google.com", 80);
try
{
sock.connect(address, 3000);
if(sock.isConnected()) status = true;
}
catch(Exception e)
{
status = false;
}
finally
{
try
{
sock.close();
}
catch(Exception e){}
}
return status;
}
I solved my problem with this code
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
onConfigurationChanged(conf);
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
iv.setImageDrawable(getResources().getDrawable(R.drawable.keyboard));
greet.setText(R.string.greet);
textView1.setText(R.string.langselection);
super.onConfigurationChanged(newConfig);
}
Here's one suggestion:
public interface Service<T,U> {
T executeService(U... args);
}
public class MyService implements Service<String, Integer> {
@Override
public String executeService(Integer... args) {
// do stuff
return null;
}
}
Because of type erasure any class will only be able to implement one of these. This eliminates the redundant method at least.
It's not an unreasonable interface that you're proposing but I'm not 100% sure of what value it adds either. You might just want to use the standard Callable
interface. It doesn't support arguments but that part of the interface has the least value (imho).
The JSON spec says you CAN escape forward slash, but you don't have to.
The dependencies you have in your project, will add their own permissions. Please do the below to find from where "READ_PHONE_STATE" is coming.
IMPORTANT:
We have been using the function as provided above by LPG.
However, this contains a bug you might encounter when you start a process that generates a lot of output. Due to this you might end up with a deadlock when using this function. Instead use the adapted version below:
Function Execute-Command ($commandTitle, $commandPath, $commandArguments)
{
Try {
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $commandPath
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $commandArguments
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
[pscustomobject]@{
commandTitle = $commandTitle
stdout = $p.StandardOutput.ReadToEnd()
stderr = $p.StandardError.ReadToEnd()
ExitCode = $p.ExitCode
}
$p.WaitForExit()
}
Catch {
exit
}
}
Further information on this issue can be found at MSDN:
A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardError.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardError stream.
Here is a partial solution to your linked list class, I have left the rest of the implementation to you, and also left the good suggestion to add a tail node as part of the linked list to you as well.
The node file :
public class Node
{
private Object data;
private Node next;
public Node(Object d)
{
data = d ;
next = null;
}
public Object GetItem()
{
return data;
}
public Node GetNext()
{
return next;
}
public void SetNext(Node toAppend)
{
next = toAppend;
}
}
And here is a Linked List file :
public class LL
{
private Node head;
public LL()
{
head = null;
}
public void AddToEnd(String x)
{
Node current = head;
// as you mentioned, this is the base case
if(current == null) {
head = new Node(x);
head.SetNext(null);
}
// you should understand this part thoroughly :
// this is the code that traverses the list.
// the germane thing to see is that when the
// link to the next node is null, we are at the
// end of the list.
else {
while(current.GetNext() != null)
current = current.GetNext();
// add new node at the end
Node toAppend = new Node(x);
current.SetNext(toAppend);
}
}
}
You can change the linter for Python extension for Visual Studio Code.
In VS open the Command Palette Ctrl+Shift+P and type in one of the following commands:
Python: Select Linter
when you select a linter it will be installed. I tried flake8 and it seems issue resolved for me.
If Duff's device doesn't need a goto, then neither should you! ;)
void dsend(int count) {
int n;
if (!count) return;
n = (count + 7) / 8;
switch (count % 8) {
case 0: do { puts("case 0");
case 7: puts("case 7");
case 6: puts("case 6");
case 5: puts("case 5");
case 4: puts("case 4");
case 3: puts("case 3");
case 2: puts("case 2");
case 1: puts("case 1");
} while (--n > 0);
}
}
code above from Wikipedia entry.
Yes, it is 128, except for temp tables, whose names can only be up to 116 character long. It is perfectly explained here.
And the verification can be easily made with the following script contained in the blog post before:
DECLARE @i NVARCHAR(800)
SELECT @i = REPLICATE('A', 116)
SELECT @i = 'CREATE TABLE #'+@i+'(i int)'
PRINT @i
EXEC(@i)
CREATE FUNCTION dbo.UFN_GET_SQL_SEVER_VERSION
(
)
RETURNS sysname
AS
BEGIN
DECLARE @ServerVersion sysname, @ProductVersion sysname, @ProductLevel sysname, @Edition sysname;
SELECT @ProductVersion = CONVERT(sysname, SERVERPROPERTY('ProductVersion')),
@ProductLevel = CONVERT(sysname, SERVERPROPERTY('ProductLevel')),
@Edition = CONVERT(sysname, SERVERPROPERTY ('Edition'));
--see: http://support2.microsoft.com/kb/321185
SELECT @ServerVersion =
CASE
WHEN @ProductVersion LIKE '8.00.%' THEN 'Microsoft SQL Server 2000'
WHEN @ProductVersion LIKE '9.00.%' THEN 'Microsoft SQL Server 2005'
WHEN @ProductVersion LIKE '10.00.%' THEN 'Microsoft SQL Server 2008'
WHEN @ProductVersion LIKE '10.50.%' THEN 'Microsoft SQL Server 2008 R2'
WHEN @ProductVersion LIKE '11.0%' THEN 'Microsoft SQL Server 2012'
WHEN @ProductVersion LIKE '12.0%' THEN 'Microsoft SQL Server 2014'
END
RETURN @ServerVersion + N' ('+@ProductLevel + N'), ' + @Edition + ' - ' + @ProductVersion;
END
GO
you can't animate every property,
here's a reference to which are the animatable properties
visibility is animatable while display isn't...
in your case you could also animate opacity
or height
depending of the kind of effect you want to render_
You can simply create a new Photoshop document and set its default background to White instead of Transparent. Then, copy and paste your image to the newly created document and save it.
You should take a look the reference documentation. It's well explained.
In your case, I think you cannot use between because you need to pass two parameters
Between - findByStartDateBetween … where x.startDate between ?1 and ?2
In your case take a look to use a combination of LessThan
or LessThanEqual
with GreaterThan
or GreaterThanEqual
LessThan - findByEndLessThan … where x.start< ?1
LessThanEqual findByEndLessThanEqual … where x.start <= ?1
GreaterThan - findByStartGreaterThan … where x.end> ?1
GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1
You can use the operator And
and Or
to combine both.
In a nutshell, the more a programming style emphasizes What (to do) abstracting away the details of How (to do it) the more that style is considered to be declarative. The opposite is true for imperative. Functional programming is associated with the declarative style.
here is linked a bitter article by Joel Spolsky, but contains a good distinction between toolboxes, libraries, frameworks and such
I realize that I is kinda late, but still better late than never. I was having similar problem recently. I used XMLWriter
to subsequently update XML file and was receiving the same errors. I found the clean solution for this:
The XMLWriter
uses underlying FileStream
to access the modified file. Problem is that when you call XMLWriter.Close()
method, the underlying stream doesn't get closed and is locking the file. What you need to do is to instantiate your XMLWriter
with settings and specify that you need that underlying stream closed.
Example:
XMLWriterSettings settings = new Settings();
settings.CloseOutput = true;
XMLWriter writer = new XMLWriter(filepath, settings);
Hope it helps.
Try this:
bool matchFound = myList.Any(s => s.Contains("Mdd LH"));
The Any()
will stop searching the moment it finds a match, so is quite efficient for this task.
Run this in the command line (or git bash on windows):
echo "" > $(npm config get userconfig)
npm config edit
echo "" > $(npm config get globalconfig)
npm config --global edit
sudo sh -c 'echo "" > $(npm config get globalconfig)'
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
Extension method based on Linq
public static void DeleteRows(this DataTable dt, Func<DataRow, bool> predicate)
{
foreach (var row in dt.Rows.Cast<DataRow>().Where(predicate).ToList())
row.Delete();
}
Then use:
DataTable dt = GetSomeData();
dt.DeleteRows(r => r.Field<double>("Amount") > 123.12 && r.Field<string>("ABC") == "XYZ");
Make sure you register Spring's CharacterEncodingFilter
in your web.xml
(must be the first filter in that file).
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
If you are on Tomcat you might not have set the URIEncoding
in your server.xml
. If you don't set it to UTF-8 it won't work. Definitely keep the CharacterEncodingFilter
. Nevertheless, here's a concise checklist to follow. It will definitely guide you to make this work.
I was getting the same error when trying through windows authentication. Sounds ludicrous but just in case it helps someone else: it was because my domain account got locked somehow while I was still logged in (!). Unlocking the account fixed it.
You may supply extra argument for confirming a new image is posted.
Something like:
def save(self, new_image=False, *args, **kwargs):
if new_image:
small=rescale_image(self.image,width=100,height=100)
self.image_small=SimpleUploadedFile(name,small_pic)
super(Model, self).save(*args, **kwargs)
or pass request variable
def save(self, request=False, *args, **kwargs):
if request and request.FILES.get('image',False):
small=rescale_image(self.image,width=100,height=100)
self.image_small=SimpleUploadedFile(name,small_pic)
super(Model, self).save(*args, **kwargs)
I think these wont break your save when called simply.
You may put this in your admin.py so that this work with admin site too (for second of above solutions):
class ModelAdmin(admin.ModelAdmin):
....
def save_model(self, request, obj, form, change):
instance = form.save(commit=False)
instance.save(request=request)
return instance
Include this dependencies in your POM.xml and run Maven -> Update
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>0.99</version>
</dependency>
Apparently, using Hibernate5Module, the @Transient will not be serialize if using ObjectMapper. Removing will make it work.
import javax.persistence.Transient;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TransientFieldTest {
@Test
public void Print_Json() throws JsonProcessingException {
ObjectMapper objectEntityMapper = new ObjectMapper();
//objectEntityMapper.registerModule(new Hibernate5Module());
objectEntityMapper.setSerializationInclusion(Include.NON_NULL);
log.info("object: {}", objectEntityMapper.writeValueAsString( //
SampleTransient.builder()
.id("id")
.transientField("transientField")
.build()));
}
@Getter
@Setter
@Builder
private static class SampleTransient {
private String id;
@Transient
private String transientField;
private String nullField;
}
}
In Mongoose: from the document:
To remove a document from a subdocument array we may pass an object with a matching _id.
contact.phone.pull({ _id: itemId }) // remove
contact.phone.pull(itemId); // this also works
See Leonid Beschastny's answer for the correct answer.
Lets say we're looking for function named foo
:
foo\s*=\s*function
(searches for foo = function
with any number of spaces between those three tokens),Another variant for function definition is function\s*foo\s*\(
for function foo(
with any number of spaces between those three tokens.
Solution is to wrap your padded div, with fixed width outer div
HTML
<div class="outer">
<div class="inner">
<!-- your content -->
</div><!-- end .inner -->
</div><!-- end .outer -->
CSS
.outer, .inner {
display: block;
}
.outer {
/* specify fixed width */
width: 300px;
padding: 0;
}
.inner {
/* specify padding, can be changed while remaining fixed width of .outer */
padding: 5px;
}
It's basically a shorthand. So instead of having to write:
this.props.dispatch(toggleTodo(id));
You would use mapDispatchToProps as shown in your example code, and then elsewhere write:
this.props.onTodoClick(id);
or more likely in this case, you'd have that as the event handler:
<MyComponent onClick={this.props.onTodoClick} />
There's a helpful video by Dan Abramov on this here: https://egghead.io/lessons/javascript-redux-generating-containers-with-connect-from-react-redux-visibletodolist
There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:
pause
to the batch file so that you can see what is happening before it exits.
.bat
files and select "edit". This will open the file in notepad.pause
.- OR -
.bat
files are located, hold down the "shift" key and right click in the white space.Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.
According to the docs:
A variable or parameter whose value is never changed after it is initialized is effectively final.
Basically, if the compiler finds a variable does not appear in assignments outside of its initialization, then the variable is considered effectively final.
For example, consider some class:
public class Foo {
public void baz(int bar) {
// While the next line is commented, bar is effectively final
// and while it is uncommented, the assignment means it is not
// effectively final.
// bar = 2;
}
}
Several factors affect speed of SFTP transfer:
use this Reload page
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}