Read the Clipboard, check against the input and the time the input is "typed". If the Clipboard has the same text and it is too fast, delete the pasted input.
You can also write these lines of code in the direct parent layout of the .xml layout file in which you have the "problem":
android:focusable="true"
android:focusableInTouchMode="true"
For example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
...
android:focusable="true"
android:focusableInTouchMode="true" >
<EditText
android:id="@+id/myEditText"
...
android:hint="@string/write_here" />
<Button
android:id="@+id/button_ok"
...
android:text="@string/ok" />
</LinearLayout>
EDIT :
Example if the EditText is contained in another layout:
<?xml version="1.0" encoding="utf-8"?>
<ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
... > <!--not here-->
... <!--other elements-->
<LinearLayout
android:id="@+id/theDirectParent"
...
android:focusable="true"
android:focusableInTouchMode="true" > <!--here-->
<EditText
android:id="@+id/myEditText"
...
android:hint="@string/write_here" />
<Button
android:id="@+id/button_ok"
...
android:text="@string/ok" />
</LinearLayout>
</ConstraintLayout>
The key is to make sure that the EditText is not directly focusable.
Bye! ;-)
for Activity in its oncreate methode insert below line
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
and for fragments in its onCreate method
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
Also if you want to do that programmatically just add the below line to the onCreate of the activity.
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE |
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE );
There are two kinds of input value: field's property and field's html attribute.
If you use keyup event and field.value you shuld get current value of the field. It's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=""). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).
fill_parent
will make the width or height of the element to be as
large as the parent element, in other words, the container.
wrap_content
will make the width or height be as large as needed to
contain the elements within it.
It's worth noting these terms have standardized, IEEE definitions, which can be searched at https://pascal.computer.org/.
abstraction
information hiding
encapsulation
first use this:
LayoutInflater inflater = (LayoutInflater) Read_file.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Read file is current activity in which you want your context.
View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));
then you can use this to find any element in layout.
ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);
WARNING: Not for git newbies.
This comes up enough in my workflow that I've almost tried to write a new git command for it. The usual git stash
flow is the way to go but is a little awkward. I usually make a new commit first since if I have been looking at the changes, all the information is fresh in my mind and it's better to just start git commit
-ing what I found (usually a bugfix belonging on master that I discover while working on a feature branch) right away.
It is also helpful—if you run into situations like this a lot—to have another working directory alongside your current one that always have the
master
branch checked out.
So how I achieve this goes like this:
git commit
the changes right away with a good commit message.git reset HEAD~1
to undo the commit from current branch.Sometimes later (asynchronously), or immediately in another terminal window:
cd my-project-master
which is another WD sharing the same .git
git reflog
to find the bugfix I've just made.git cherry-pick SHA1
of the commit.Optionally (still asynchronous) you can then rebase (or merge) your feature branch to get the bugfix, usually when you are about to submit a PR and have cleaned your feature branch and WD already:
cd my-project
which is the main WD I'm working on.git rebase master
to get the bugfixes.This way I can keep working on the feature uninterrupted and not have to worry about git stash
-ing anything or having to clean my WD before a git checkout
(and then having the check the feature branch backout again.) and still have all my bugfixes goes to master
instead of hidden in my feature branch.
IMO git stash
and git checkout
is a real PIA when you are in the middle of working on some big feature.
The standard way to catch null
and undefined
simultaneously is this:
if (variable == null) {
// do something
}
--which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) {
// do something
}
When writing professional JS, it's taken for granted that type equality and the behavior of ==
vs ===
is understood. Therefore we use ==
and only compare to null
.
The comments suggesting the use of typeof
are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try
/catch
if you are working with input you don't have control over.
You should not have any references to undeclared variables in your code.
How about this:
find /some/directory -maxdepth 1 -type f -exec cmd option {} \; > results.out
-maxdepth 1
argument prevents find from recursively descending into
any subdirectories. (If you want such nested directories to get processed, you can omit this.)-type -f
specifies that only plain files will be processed.-exec cmd option {}
tells it to run cmd
with the specified option
for each file found, with the filename substituted for {}
\;
denotes the end of the command.cmd
executions is redirected to
results.out
However, if you care about the order in which the files are processed, you
might be better off writing a loop. I think find
processes the files
in inode order (though I could be wrong about that), which may not be what
you want.
I'm using bootstrap.
I used css parameters.
.table {
table-layout:fixed;
}
.table td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
and bootstrap grid system parameters, like this.
<th class="col-sm-2">Name</th>
<td class="col-sm-2">hoge</td>
REPLACE INTO
pros:
cons:
too slow.
auto-increment key will CHANGE(increase by 1) if there is entry matches unique key
or primary key
, because it deletes the old entry then insert new one.
INSERT IGNORE
pros:
cons:
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
some other errors/warnings will be ignored such as data conversion error.
INSERT ... ON DUPLICATE KEY UPDATE
pros:
cons:
looks relatively complex if you just want to insert not update.
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
unique key
or primary key
?As mentioned in the comment below by @toien: "auto-increment column will be effected depends on innodb_autoinc_lock_mode
config after version 5.1" if you are using innodb
as your engine, but this also effects concurrency, so it needs to be well considered before used. So far I'm not seeing any better solution.
In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.
function redirection()
{
<?php $send=$_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location = redirect_to;
}
g.next()
has been renamed to g.__next__()
. The reason for this is consistency: special methods like __init__()
and __del__()
all have double underscores (or "dunder" in the current vernacular), and .next()
was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]
But instead of calling g.__next__()
, use next(g)
.
[*] There are other special attributes that have gotten this fix; func_name
, is now __name__
, etc.
FatJar can help you in this case.
In addition to the"Export as Jar" function which is included to Eclipse the Plug-In bundles all dependent JARs together into one executable jar.
The Plug-In adds the Entry "Build Fat Jar" to the Context-Menu of Java-projects
This is useful if your final exported jar includes other external jars.
If you have Ganymede, the Export Jar dialog is enough to export your resources from your project.
After Ganymede, you have:
The best and most accurate method I found was to download the bfg.jar file: https://rtyley.github.io/bfg-repo-cleaner/
Then run the commands:
git clone --bare https://project/repository project-repository
cd project-repository
java -jar bfg.jar --delete-folders DIRECTORY_NAME
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --mirror https://project/new-repository
If you want to delete files then use the delete-files option instead:
java -jar bfg.jar --delete-files *.pyc
I had the same problem and I added tx:annotation-driven
in applicationContext.xml
and it worked.
First loop
$v = $a[0];
$v = $a[1];
$v = $a[2];
$v = $a[3];
Yes! Current $v
= $a[3]
position.
Second loop
$a[3] = $v = $a[0], echo $v; // same as $a[3] and $a[0] == 'zero'
$a[3] = $v = $a[1], echo $v; // same as $a[3] and $a[1] == 'one'
$a[3] = $v = $a[2], echo $v; // same as $a[3] and $a[2] == 'two'
$a[3] = $v = $a[3], echo $v; // same as $a[3] and $a[3] == 'two'
because $a[3]
is assigned by before processing.
I have created a utility function (tested once on a device where I was getting an incorrect country code based on locale).
Reference: CountryCodePicker.java
fun getDetectedCountry(context: Context, defaultCountryIsoCode: String): String {
detectSIMCountry(context)?.let {
return it
}
detectNetworkCountry(context)?.let {
return it
}
detectLocaleCountry(context)?.let {
return it
}
return defaultCountryIsoCode
}
private fun detectSIMCountry(context: Context): String? {
try {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
Log.d(TAG, "detectSIMCountry: ${telephonyManager.simCountryIso}")
return telephonyManager.simCountryIso
}
catch (e: Exception) {
e.printStackTrace()
}
return null
}
private fun detectNetworkCountry(context: Context): String? {
try {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
Log.d(TAG, "detectNetworkCountry: ${telephonyManager.simCountryIso}")
return telephonyManager.networkCountryIso
}
catch (e: Exception) {
e.printStackTrace()
}
return null
}
private fun detectLocaleCountry(context: Context): String? {
try {
val localeCountryISO = context.getResources().getConfiguration().locale.getCountry()
Log.d(TAG, "detectNetworkCountry: $localeCountryISO")
return localeCountryISO
}
catch (e: Exception) {
e.printStackTrace()
}
return null
}
answer = “True”
myvars = “the answer is” + answer
print(myvars)
That should give you the answer is True easily as you have stored answer as a string by using the quotation marks
Javascript string objects have a toLocaleUpperCase()
function that makes the conversion itself easy.
Here's an example of live capitalisation:
$(function() {
$('input').keyup(function() {
this.value = this.value.toLocaleUpperCase();
});
});
Unfortunately, this resets the textbox contents completely, so the user's caret position (if not "the end of the textbox") is lost.
You can hack this back in, though, with some browser-switching magic:
// Thanks http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
function getCaretPosition(ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
CaretPos = ctrl.selectionStart;
}
return CaretPos;
}
function setCaretPosition(ctrl, pos) {
if (ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
// The real work
$(function() {
$('input').keyup(function() {
// Remember original caret position
var caretPosition = getCaretPosition(this);
// Uppercase-ize contents
this.value = this.value.toLocaleUpperCase();
// Reset caret position
// (we ignore selection length, as typing deselects anyway)
setCaretPosition(this, caretPosition);
});
});
Ultimately, it might be easiest to fake it. Set the style text-transform: uppercase
on the textbox so that it appears uppercase to the user, then in your Javascript apply the text transformation once whenever the user's caret focus leaves the textbox entirely:
HTML:
<input type="text" name="keywords" class="uppercase" />
CSS:
input.uppercase { text-transform: uppercase; }
Javascript:
$(function() {
$('input').focusout(function() {
// Uppercase-ize contents
this.value = this.value.toLocaleUpperCase();
});
});
Hope this helps.
I started with a demo app and modified it. I change the java path inside source from com -> example -> foo to my own and edited the manifest; however, Android Studio (0.8.7) got very confused.
I tried everything listed above and none of it worked for me. Maybe it even made things worse?
My final solution was to edit <projectname>.iml
in the .idea
subdirectory by opening it up in Android Studio (aka text editor).
Before:
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" generated="true" />
</content>
I (re)added the src directory (2nd line). After:
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" generated="true" />
</content>
After saving it, Android Studio reloaded and started functioning as expected.
Besides calling omp_get_num_threads()
outside of the parallel region in your case, calling omp_set_num_threads()
still doesn't guarantee that the OpenMP runtime will use exactly the specified number of threads. omp_set_num_threads()
is used to override the value of the environment variable OMP_NUM_THREADS
and they both control the upper limit of the size of the thread team that OpenMP would spawn for all parallel regions (in the case of OMP_NUM_THREADS
) or for any consequent parallel region (after a call to omp_set_num_threads()
). There is something called dynamic teams that could still pick smaller number of threads if the run-time system deems it more appropriate. You can disable dynamic teams by calling omp_set_dynamic(0)
or by setting the environment variable OMP_DYNAMIC
to false
.
To enforce a given number of threads you should disable dynamic teams and specify the desired number of threads with either omp_set_num_threads()
:
omp_set_dynamic(0); // Explicitly disable dynamic teams
omp_set_num_threads(4); // Use 4 threads for all consecutive parallel regions
#pragma omp parallel ...
{
... 4 threads used here ...
}
or with the num_threads
OpenMP clause:
omp_set_dynamic(0); // Explicitly disable dynamic teams
// Spawn 4 threads for this parallel region only
#pragma omp parallel ... num_threads(4)
{
... 4 threads used here ...
}
JSON is JavaScript Object Notation. It is a much-more compact way of transmitting sets of data across network connections as compared to XML. I suggest JSON be used in any AJAX-like applications where XML would otherwise be the "recommended" option. The verbosity of XML will add to download time and increased bandwidth consumption ($$$). You can accomplish the same effect with JSON and its mark-up is almost exclusively dedicated to the data itself and not the underlying structure.
Check the exact driver name in the ODBC Administrator tool. Press Windows key + R and then:
C:\Windows\System32\odbcad32.exe
on 32-bit systemsC:\Windows\SysWOW64\odbcad32.exe
on 64-bit systemsIn my case it should have been Microsoft Access Driver (*.mdb, *.accdb)
instead of Microsoft Access Driver (*.mdb)
.
Use CTRL + ] to switch between them. Place the cursor at one of the braces when using it.
Try this:
for (var i in tracks[racer_id].data.points) {
values = tracks[racer_id].data.points[i];
point = new google.maps.LatLng(values.lat, values.lng);
if (values.qst) {
var marker = new google.maps.Marker({map: map, position: point, clickable: true});
tracks[racer_id].markers[i] = marker;
var info = new google.maps.InfoWindow({
content: '<b>Speed:</b> ' + values.inst + ' knots'
});
tracks[racer_id].info[i] = info;
google.maps.event.addListener(tracks[racer_id].markers[i], 'click', function() {
tracks[racer_id].info[i].open(map, tracks[racer_id].markers[i]);
});
}
track_coordinates.push(point);
bd.extend(point);
}
I prefer to do the following one-liner, in POSIX shell compatible format:
$ [ -f "/$DIR/$FILE" ] || echo "$FILE NOT FOUND"
$ [ -f "/$DIR/$FILE" ] && echo "$FILE FOUND"
For a couple of commands, like I would do in a script:
$ [ -f "/$DIR/$FILE" ] || { echo "$FILE NOT FOUND" ; exit 1 ;}
Once I started doing this, I rarely use the fully typed syntax anymore!!
WCF = Windows Communication Foundation is used to build service-oriented applications. WPF = Windows Presentation Foundation is used to write platform-independent applications.
Since :last-child
is a CSS3 pseudo-class, it is not supported in IE8. I believe :first-child
is supported, as it's defined in the CSS2.1 specification.
One possible solution is to simply give the last child a class name and style that class.
Another would be to use JavaScript. jQuery makes this particularly easy as it provides a :last-child
pseudo-class which should work in IE8. Unfortunately, that could result in a flash of unstyled content while the DOM loads.
+----------------------------------------------------------------------------------------------+
¦ ¦ foreach ¦ map ¦
¦----------------+-------------------------------------+---------------------------------------¦
¦ Functionality ¦ Performs given operation on each ¦ Performs given "transformation" on ¦
¦ ¦ element of the array ¦ "copy" of each element ¦
¦————————————————+—————————————————————————————————————+———————————————————————————————————————¦
¦ Return value ¦ Returns undefined ¦ Returns new array with tranformed ¦
¦ ¦ ¦ elements leaving back original array ¦
¦ ¦ ¦ unchanged ¦
¦————————————————+—————————————————————————————————————+———————————————————————————————————————¦
¦ Preferrable ¦ Performing non—transformation like ¦ Obtaining array containing output of ¦
¦ usage scenario ¦ processing on each element. ¦ some processing done on each element ¦
¦ and example ¦ ¦ of the array. ¦
¦ ¦ For example, saving all elements in ¦ ¦
¦ ¦ the database ¦ For example, obtaining array of ¦
¦ ¦ ¦ lengths of each string in the ¦
¦ ¦ ¦ array ¦
+----------------------------------------------------------------------------------------------+
$_POST is already an array, so you don't need to wrap array() around it.
Try this instead:
<?php
for ($i=0;$i<count($_POST['id']);$i++) {
echo "<p>".$_POST['id'][$i]."</p>";
echo "<p>".$_POST['value'][$i]."</p>";
echo "<hr />";
}
?>
NOTE: This works because your id
and value
arrays are symmetrical. If they had different numbers of elements then you'd need to take a different approach.
Why not just use .show()/.hide()
instead?
$("#menu").hover(function(){
$('.flyout').show();
},function(){
$('.flyout').hide();
});
Such error happens when,
1. You misspell module name which you injected.
2. If you missed to include js file of that module.
Sometimes people write js file name instead of the module name which we are injecting.
In these cases what happens is angular tries to look for the module provided in the square bracket []. If it doesn't find the module, it throws error.
On this page, the Arduino sketch defines a couple of Structs (plus a couple of methods) which are then called in the setup loop and main loop. Simple enough to interpret, even for a barely-literate programmer like me.
The problems may happen because of memory issue. java.lang.OutOfMemoryError: Java heap space
please verify the logfile, any issues related to hardware(memory).
Have a look at this excellent article at CSS-Tricks:
Taken from the article:
The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution.
Just like how pixels are dead-accurate on monitors for font-sizing, point sizes are dead-accurate on paper. For the best cross-browser and cross-platform results while printing pages, set up a print stylesheet and size all fonts with point sizes.
For good measure, the reason we don't use point sizes for screen display (other than it being absurd), is that the cross-browser results are drastically different:
If you need fine-grained control, sizing fonts in pixel values (px) is an excellent choice (it's my favorite). On a computer screen, it doesn't get any more accurate than a single pixel. With sizing fonts in pixels, you are literally telling browsers to render the letters exactly that number of pixels in height:
Windows, Mac, aliased, anti-aliased, cross-browsers, doesn't matter, a font set at 14px will be 14px tall. But that isn't to say there won't still be some variation. In a quick test below, the results were slightly more consistent than with keywords but not identical:
Due to the nature of pixel values, they do not cascade. If a parent element has an 18px pixel size and the child is 16px, the child will be 16px. However, font-sizing settings can be using in combination. For example, if the parent was set to 16px and the child was set to larger, the child would indeed come out larger than the parent. A quick test showed me this:
"Larger" bumped the 16px of the parent into 20px, a 25% increase.
Pixels have gotten a bad wrap in the past for accessibility and usability concerns. In IE 6 and below, font-sizes set in pixels cannot be resized by the user. That means that us hip young healthy designers can set type in 12px and read it on the screen just fine, but when folks a little longer in the tooth go to bump up the size so they can read it, they are unable to. This is really IE 6's fault, not ours, but we gots what we gots and we have to deal with it.
Setting font-size in pixels is the most accurate (and I find the most satisfying) method, but do take into consideration the number of visitors still using IE 6 on your site and their accessibility needs. We are right on the bleeding edge of not needing to care about this anymore.
If escaping your single quote with another single quote isn't working for you (like it didn't for one of my recent REPLACE() queries), you can use SET QUOTED_IDENTIFIER OFF before your query, then SET QUOTED_IDENTIFIER ON after.
For example
SET QUOTED_IDENTIFIER OFF;
UPDATE TABLE SET NAME = REPLACE(NAME, "'S", "S");
SET QUOTED_IDENTIFIER OFF;
When you do this,
while((inputLine = buff_read.readLine())!= null){
System.out.println(inputLine);
}
You consume everything in instream, so instream is empty. Now when try to do this,
Document doc = builder.parse(instream);
The parsing will fail, because you have passed it an empty stream.
I was getting the same error in IE7/IE8. Worked fine in all other browsers including IE9/IE10.
What I found worked for me was eliminating self closing tags.
Bad
<div>
<span data-bind="text: name"/>
</div>
Good
<div>
<span data-bind="text: name"></span>
</div>
This expands on the answer by Denis Bubnov.
I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.
{% set count = 0 %}
{% for anchor in items %}
{% if anchor.content['#paragraph'].field_anchor_link.0.value %}
{% set count = count + 1 %}
{% endif %}
{% endfor %}
{% if count > 0 %}
--- build the toc here --
{% endif %}
If you just need to remove the last set color, the following might suit you.
In my situation, I needed to add a color class to the body tag on a click event and remove the last color that was set. In that case, you store the current color, and then look up the data tag to remove the last set color.
Code:
var colorID = 'Whatever your new color is';
var bodyTag = $('body');
var prevColor = bodyTag.data('currentColor'); // get current color
bodyTag.removeClass(prevColor);
bodyTag.addClass(colorID);
bodyTag.data('currentColor',colorID); // set the new color as current
Might not be exactly what you need, but for me it was and this was the first SO question I looked at, so thought I would share my solution in case it helps anyone.
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
This might help you.
<form id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="save()" />
</form>
<script>
function save(){
$('#myinput').val('1');
$('#form').submit();
}
</script>
mysqli is the enhanced version of mysql.
PDO extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions.
Simple: active the accordion to a class, and then create divs with this, like multiples instances of accordion.
Like this:
JS
$(function() {
$( ".accordion" ).accordion({
collapsible: true,
clearStyle: true,
active: false,
})
});
HTML
<div class="accordion">
<h3>Title</h3>
<p>lorem</p>
</div>
<div class="accordion">
<h3>Title</h3>
<p>lorem</p>
</div>
<div class="accordion">
<h3>Title</h3>
<p>lorem</p>
</div>
Use the View's post method like this
post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "width " + MyView.this.getMeasuredWidth());
}
});
For Windows users looking for solution of same problem. I just repleced
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"
in my /conf/extra/http?-xampp.conf
An easy way to compare strings that are only different by lowercase and capitalized characters is to do an ascii comparison. All capital and lowercase letters differ by 32 bits in the ascii table, using this information we have the following...
for( int i = 0; i < string2.length(); i++)
{
if (string1[i] == string2[i] || int(string1[i]) == int(string2[j])+32 ||int(string1[i]) == int(string2[i])-32)
{
count++;
continue;
}
else
{
break;
}
if(count == string2.length())
{
//then we have a match
}
}
The following lines work just fine...
var headerHeight = $( '#header' ).height();
var footerHeight = $( '#footer' ).height();
var footerTop = $( '#footer' ).offset().top;
var height = ( footerTop - ( headerHeight + footerHeight ) );
$( '#content' ).height( height );
Wherever you want vertically center style means you can try display:table-cell
and vertical-align:middle
.
Example:
#box_x000D_
{_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
height: 90px;_x000D_
width: 270px;_x000D_
background: #000;_x000D_
font-size: 48px;_x000D_
font-style: oblique;_x000D_
color: #FFF;_x000D_
text-align: center;_x000D_
margin-top: 20px;_x000D_
margin-left: 5px;_x000D_
}
_x000D_
<div Id="box">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit._x000D_
</div>
_x000D_
This solved my problem.
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, {useUnifiedTopology: true});
Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.
Based on what it looks like you're trying to do, this will not work.
These arrays belong in your main class.
I was in a situation where I was looking for -s theirs
but of course, this strategy doesn't exist. My history was that I had forked a project on GitHub, and now for some reason, my local master
could not be merged with upstream/master
although I had made no local changes to this branch. (Really don't know what happened there -- I guess upstream had done some dirty pushes behind the scenes, maybe?)
What I ended up doing was
# as per https://help.github.com/articles/syncing-a-fork/
git fetch upstream
git checkout master
git merge upstream/master
....
# Lots of conflicts, ended up just abandonging this approach
git reset --hard # Ditch failed merge
git checkout upstream/master
# Now in detached state
git branch -d master # !
git checkout -b master # create new master from upstream/master
So now my master
is again in sync with upstream/master
(and you could repeat the above for any other branch you also want to sync similarly).
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
lets say the objects array is referenced by the variable users
If ES6 can be used then the easiest solution will be:
users.map(user => user.name).join(', ');
If not, and lodash can be used so :
_.map(users, function(user) {
return user.name;
}).join(', ');
Take a look at the ISNULL function. It helps you replace NULL values for other values. http://msdn.microsoft.com/en-us/library/ms184325.aspx
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
Firefox contains a dns cache. To disable the DNS cache:
When disabled, Firefox will use the DNS cache provided by the OS.
You can try this:-
string values = "";
foreach(ListItem item in myCBL.Items){
if(item.Selected)
{
values += item.Value.ToString() + ",";
}
}
values = values.TrimEnd(','); //To eliminate comma in last.
Follow the example --
songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]
print("===========================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')
playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')
# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))
I would rather use plt.clf()
after every plt.show()
to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.
Similarly, you could do plt.cla()
to just clear the current axes.
To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0, 1].clear()
Similar issue, using this "borrowed" and slightly modified code:
Intent intent = new Intent(Intent.ACTION_VIEW);
File newApk = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "myapp.apk");
intent.setDataAndType(Uri.fromFile(newApk), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
result = true;
Needed to change the file creation to this (comma instead of plus in the File constructor, was missing '/' after the download directory):
File newApk = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "myapp.apk");
When condition is really complex I use the following style (PHP real life example):
if( $format_bool &&
(
( isset( $column_info['native_type'] )
&& stripos( $column_info['native_type'], 'bool' ) !== false
)
|| ( isset( $column_info['driver:decl_type'] )
&& stripos( $column_info['driver:decl_type'], 'bool' ) !== false
)
|| ( isset( $column_info['pdo_type'] )
&& $column_info['pdo_type'] == PDO::PARAM_BOOL
)
)
)
I believe it's more nice and readable than nesting multiple levels of if()
. And in some cases like this you simply can't break complex condition into pieces because otherwise you would have to repeat the same statements in if() {...}
block many times.
I also believe that adding some "air" into code is always a good idea. It improves readability greatly.
To get Tkinter input from the text box, you must add a few more attributes to the normal .get()
function. If we have a text box myText_Box
, then this is the method for retrieving its input.
def retrieve_input():
input = self.myText_Box.get("1.0",END)
The first part, "1.0"
means that the input should be read from line one, character zero (ie: the very first character). END
is an imported constant which is set to the string "end"
. The END
part means to read until the end of the text box is reached. The only issue with this is that it actually adds a newline to our input. So, in order to fix it we should change END
to end-1c
(Thanks Bryan Oakley) The -1c
deletes 1 character, while -2c
would mean delete two characters, and so on.
def retrieve_input():
input = self.myText_Box.get("1.0",'end-1c')
This function gives all 4 limits of the used range:
Function FindUsedRangeLimits()
Set Sheet = ActiveSheet
Sheet.UsedRange.Select
' Display the range's rows and columns.
row_min = Sheet.UsedRange.Row
row_max = row_min + Sheet.UsedRange.Rows.Count - 1
col_min = Sheet.UsedRange.Column
col_max = col_min + Sheet.UsedRange.Columns.Count - 1
MsgBox "Rows " & row_min & " - " & row_max & vbCrLf & _
"Columns: " & col_min & " - " & col_max
LastCellBeforeBlankInColumn = True
End Function
You can also define case insensitive during the pattern compile:
pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)
Try a list comprehension:
l = [x * 2 for x in l]
This goes through l
, multiplying each element by two.
Of course, there's more than one way to do it. If you're into lambda functions and map
, you can even do
l = map(lambda x: x * 2, l)
to apply the function lambda x: x * 2
to each element in l
. This is equivalent to:
def timesTwo(x):
return x * 2
l = map(timesTwo, l)
Note that map()
returns a map object, not a list, so if you really need a list afterwards you can use the list()
function afterwards, for instance:
l = list(map(timesTwo, l))
Thanks to Minyc510 in the comments for this clarification.
if in case you are not using name in input but other element, then you can target other element with there attribute.
[title~=flower] {_x000D_
border: 5px solid yellow;_x000D_
}
_x000D_
<img src="klematis.jpg" title="klematis flower" width="150" height="113">_x000D_
<img src="img_flwr.gif" title="flower" width="224" height="162">_x000D_
<img src="img_flwr.gif" title="flowers" width="224" height="162">
_x000D_
hope its help. Thank you
Example:
>>> {1, 2, [3, 4]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> {1, 2, (3, 4)}
set([1, 2, (3, 4)])
Note that hashing is somehow recursive and the above holds true for nested items:
>>> {1, 2, 3, (4, [2, 3])}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Dict keys also are hashable, so the above holds for dict keys too.
for me the problem was solved by installing another supportive package.
so I installed graphviz package through anaconda then I failed to import it
after that I installed a second package named python-graphviz
also through anaconda
then I succeeded in importing graphviz
module into my code
I hope this will help someone :)
There could be two easy solutions:
Should you want to clear the array with something other than a value, std::file wont cut it; instead I found std::generate useful. e.g. I had a vector of lists I wanted to initialize
std::generate(v.begin(), v.end(), [] () { return std::list<X>(); });
You can do ints too e.g.
std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });
or just
std::generate(v.begin(), v.end(), [] (){ return 0; });
but I imagine std::fill is faster for the simplest case
try with \w
http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
You are almost certainly using a different version of the class at runtime to the one you expect. In particular, the runtime class would be different to the one you've compiled against (else this would have caused a compile-time error) - has that method ever been private
? Do you have old versions of the classes/jars on your system anywhere?
As the javadocs for IllegalAccessError
state,
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
I'd definitely look at your classpath and check whether it holds any surprises.
Try this code...
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
Here is another way of proxying when you need more flexibility:
You can use the 'router' option and some javascript code to rewrite the target URL dynamically. For this, you need to specify a javascript file instead of a json file as the --proxy-conf parameter in your 'start' script parameter list:
"start": "ng serve --proxy-config proxy.conf.js --base-href /"
As shown above, the --base-href parameter also needs to be set to / if you otherwise set the <base href="..."> to a path in your index.html. This setting will override that and it's necessary to make sure URLs in the http requests are correctly constructed.
Then you need the following or similar content in your proxy.conf.js (not json!):
const PROXY_CONFIG = {
"/api/*": {
target: https://www.mydefaulturl.com,
router: function (req) {
var target = 'https://www.myrewrittenurl.com'; // or some custom code
return target;
},
changeOrigin: true,
secure: false
}
};
module.exports = PROXY_CONFIG;
Note that the router option can be used in two ways. One is when you assign an object containing key value pairs where the key is the requested host/path to match and the value is the rewritten target URL. The other way is when you assign a function with some custom code, which is what I'm demonstrating in my examples here. In the latter case I found that the target option still needs to be set to something in order for the router option to work. If you assign a custom function to the router option then the target option is not used so it could be just set to true. Otherwise, it needs to be the default target URL.
Webpack uses http-proxy-middleware so you'll find useful documentation there: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md#http-proxy-middleware-options
The following example will get the developer name from a cookie to determine the target URL using a custom function as router:
const PROXY_CONFIG = {
"/api/*": {
target: true,
router: function (req) {
var devName = '';
var rc = req.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
if(parts.shift().trim() == 'dev') {
devName = decodeURI(parts.join('='));
}
});
var target = 'https://www.'+ (devName ? devName + '.' : '' ) +'mycompany.com';
//console.log(target);
return target;
},
changeOrigin: true,
secure: false
}
};
module.exports = PROXY_CONFIG;
(The cookie is set for localhost and path '/' and with a long expiry using a browser plugin. If the cookie doesn't exist, the URL will point to the live site.)
You basically want to loop through each property in the object.
var Dictionary = {
If: {
you: {
can: '',
make: ''
},
sense: ''
},
of: {
the: {
sentence: {
it: '',
worked: ''
}
}
}
};
function Iterate(obj) {
for (prop in obj) {
if (obj.hasOwnProperty(prop) && isNaN(prop)) {
console.log(prop + ': ' + obj[prop]);
Iterate(obj[prop]);
}
}
}
Iterate(Dictionary);
This works for everyone:
pip install -r /path/to/requirements.txt
Try this sample SQL scripts for easy understanding,
CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))
--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2
INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'
INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'
SELECT * FROM TABLE1
SELECT * FROM TABLE2
DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO
Your case is:
DELETE pgc
FROM guide_category pgc
LEFT JOIN guide g
ON g.id_guide = gc.id_guide
WHERE g.id_guide IS NULL
The answer provided by @Jean provides a working but obscure solution (although it doesn't handle trailing spaces)
As an alternative consider a vba user defined function (UDF)
Function RightWord(r As Range) As Variant
Dim s As String
s = Trim(r.Value)
RightWord = Mid(s, InStrRev(s, " ") + 1)
End Function
Use in sheet as
=RightWord(A2)
What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:
-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);
If you are searching a string, go for the LIKE operator (but this will be slow):
-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';
If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:
-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';
While I was having trouble join those two tables, I got away with doing exactly what I wanted by opening both remote databases at the same time. MySQL 5.6 (php 7.1) and the other MySQL 5.1 (php 5.6)
//Open a new connection to the MySQL server
$mysqli1 = new mysqli('server1','user1','password1','database1');
$mysqli2 = new mysqli('server2','user2','password2','database2');
//Output any connection error
if ($mysqli1->connect_error) {
die('Error : ('. $mysqli1->connect_errno .') '. $mysqli1->connect_error);
} else {
echo "DB1 open OK<br>";
}
if ($mysqli2->connect_error) {
die('Error : ('. $mysqli2->connect_errno .') '. $mysqli2->connect_error);
} else {
echo "DB2 open OK<br><br>";
}
If you get those two OKs on screen, then both databases are open and ready. Then you can proceed to do your querys.
$results = $mysqli1->query("SELECT * FROM video where video_id_old is NULL");
while($row = $results->fetch_array()) {
$theID = $row[0];
echo "Original ID : ".$theID." <br>";
$doInsert = $mysqli2->query("INSERT INTO video (...) VALUES (...)");
$doGetVideoID = $mysqli2->query("SELECT video_id, time_stamp from video where user_id = '".$row[13]."' and time_stamp = ".$row[28]." ");
while($row = $doGetVideoID->fetch_assoc()) {
echo "New video_id : ".$row["video_id"]." user_id : ".$row["user_id"]." time_stamp : ".$row["time_stamp"]."<br>";
$sql = "UPDATE video SET video_id_old = video_id, video_id = ".$row["video_id"]." where user_id = '".$row["user_id"]."' and video_id = ".$theID.";";
$sql .= "UPDATE video_audio SET video_id = ".$row["video_id"]." where video_id = ".$theID.";";
// Execute multi query if you want
if (mysqli_multi_query($mysqli1, $sql)) {
// Query successful do whatever...
}
}
}
// close connection
$mysqli1->close();
$mysqli2->close();
I was trying to do some joins but since I got those two DBs open, then I can go back and forth doing querys by just changing the connection $mysqli1
or $mysqli2
It worked for me, I hope it helps... Cheers
In the medical industry, VT is used as the start of frame character in the MLLP/LLP/HLLP protocols that are used to frame HL-7 data, which has been a standard for medical exchange since the late 80s and is still in wide use.
Note that there is a difference between a cast to long
and a cast to Long
. If you cast to long
(a primitive value) then it should be automatically boxed to a Long
(the reference type that wraps it).
You could alternatively use new
to create an instance of Long
, initializing it with the int
value.
Updated version for Swift 3:
@IBDesignable
class FormTextField: UITextField {
@IBInspectable var paddingLeft: CGFloat = 0
@IBInspectable var paddingRight: CGFloat = 0
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + paddingLeft, y: bounds.origin.y, width: bounds.size.width - paddingLeft - paddingRight, height: bounds.size.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds: bounds)
}
}
If you're using RestangularV2
to post to a spring controller in java you can get this exception if you use RestangularV2.one()
instead of RestangularV2.all()
Similarly to @brucexin I needed to get OS-level thread identifier (which != thread.get_ident()
) and use something like below not to depend on particular numbers and being amd64-only:
---- 8< ---- (xos.pyx)
"""module xos complements standard module os"""
cdef extern from "<sys/syscall.h>":
long syscall(long number, ...)
const int SYS_gettid
# gettid returns current OS thread identifier.
def gettid():
return syscall(SYS_gettid)
and
---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos
...
print 'my tid: %d' % xos.gettid()
this depends on Cython though.
if you are getting id from url try
$id = (isset($_GET['id']) ? $_GET['id'] : '');
if getting from form you need to use POST
method cause your form has method="post"
$id = (isset($_POST['id']) ? $_POST['id'] : '');
For php notices use isset()
or empty()
to check values exist or not or initialize variable first with blank or a value
$id= '';
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
A bit late but I tried this and it worked to make the Recaptcha responsive on screens smaller than 460px width. You can't use css selector to select elements inside the iframe. So, better use the outermost parent element which is the class g-recaptcha to basically zoom-out i.e transform the size of the entire container. Here's my code which worked:
@media(max-width:459.99px) {
.modal .g-recaptcha {
transform:scale(0.75);
-webkit-transform:scale(0.75); }
}
}
The other answers explained it well already, but I'd like to offer another experiment illustrating the nature of range objects:
>>> r = range(5)
>>> for i in r:
print(i, 2 in r, list(r))
0 True [0, 1, 2, 3, 4]
1 True [0, 1, 2, 3, 4]
2 True [0, 1, 2, 3, 4]
3 True [0, 1, 2, 3, 4]
4 True [0, 1, 2, 3, 4]
As you can see, a range object is an object that remembers its range and can be used many times (even while iterating over it), not just a one-time generator.
Your code makes no sense, maybe because it's out of context.
If you mean code like this:
$('a').click(function () {
callFunction();
return false;
});
The return false will return false to the click-event. That tells the browser to stop following events, like follow a link. It has nothing to do with the previous function call. Javascript runs from top to bottom more or less, so a line cannot affect a previous line.
Using type
:
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number(1) === 'number'; // but never use this form!
// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof always return a string
typeof String("abc") === 'string'; // but never use this form!
// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // but never use this form!
// Undefined
typeof undefined === 'undefined';
typeof blabla === 'undefined'; // an undefined variable
// Objects
typeof {a:1} === 'object';
typeof [1, 2, 4] === 'object'; // use Array.isArray or Object.prototype.toString.call to differentiate regular objects from arrays
typeof new Date() === 'object';
typeof new Boolean(true) === 'object'; // this is confusing. Don't use!
typeof new Number(1) === 'object'; // this is confusing. Don't use!
typeof new String("abc") === 'object'; // this is confusing. Don't use!
// Functions
typeof function(){} === 'function';
typeof Math.sin === 'function';
String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char letter = abc.charAt(rd.nextInt(abc.length()));
This one works as well.
Illegal State Exception is an Unchecked exception.
It indicate that method has been invoked at wrong time.
example:
Thread t = new Thread();
t.start();
//
//
t.start();
output:
Runtime Excpetion: IllegalThreadStateException
We cant start the Thread again, it will throw IllegalStateException.
A simple way to check type is to compare it with something whose type you know.
>>> a = 1
>>> type(a) == type(1)
True
>>> b = 'abc'
>>> type(b) == type('')
True
I did a test using the Chrome address bar and a $QUERY_STRING
in bash, and observed the following:
~!@$%^&*()-_=+[{]}\|;:',./?
and grave (backtick)
are passed through as plaintext.
,
"
, <
and >
are converted to %20
, %22
, %3C
and %3E
respectively.
#
is ignored, since it is used by ye olde anchor.
Personally, I'd say bite the bullet and encode with base64 :)
Create a conditional function breakpoint:
In the Breakpoints window, click New to create a new breakpoint.
On the Function tab, type Reverse for Function. Type 1 for Line, type 1 for Character, and then set Language to Basic.
Click Condition and make sure that the Condition checkbox is selected. Type instr.length > 0
for Condition, make sure that the is true option is selected, and then click OK.
In the New Breakpoint dialog box, click OK.
On the Debug menu, click Start.
First installing the framework globally on the system solved my problem.
machine@debian:/$ sudo pip install djangorestframework
or;
root@debian:/# pip install djangorestframework
node-email-templates is a much better option: https://github.com/niftylettuce/node-email-templates
it has support for windows as well
When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:
notify(int id, Notification notification)
To cancel, you would call:
cancel(int id)
with the same id. So, basically, you need to keep track of the id or possibly put the id into a Bundle you add to the Intent inside the PendingIntent?
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
Log.v("", is3g + " ConnectivityManager Test " + isWifi);
if (!is3g && !isWifi) {
Toast.makeText(
getApplicationContext(),
"Please make sure, your network connection is ON ",
Toast.LENGTH_LONG).show();
}
else {
// Put your function() to go further;
}
With this you can remove the column
and store variable
into another variable
.
df = subset(data, select = -c(genome) )
I had the same issue and took a whole day to figure out the problem. This error message by Facebook SDK is very vague. I had this problem due to openURL: method being overwritten in MyApplication. I removed the overwritten method and facebook login worked fine.
All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.
The python equivalent of NULL
is called None
(good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:
class Node:
def __init__(self): #object initializer to set attributes (fields)
self.val = 0
self.right = None
self.left = None
And then it works pretty much like you would expect:
node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()
Note that unlike in NULL
in C, None
is not a "pointer to nowhere": it is actually the only instance of class NoneType
.
Therefore, as None
is a regular object, you can test for it just like any other object:
if node.left == None:
print("The left node is None/Null.")
Although since None
is a singleton instance, it is considered more idiomatic to use is
and compare for reference equality:
if node.left is None:
print("The left node is None/Null.")
You need to declare @font-face
like this in your stylesheet
@font-face {
font-family: 'Awesome-Font';
font-style: normal;
font-weight: 400;
src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}
Now if you want to apply this font to a paragraph simply use it like this..
p {
font-family: 'Awesome-Font', Arial;
}
Using bash "here string":
$ fspec="/exp/home1/abc.txt"
$ tr "/" "\n" <<< $fspec | tail -1
abc.txt
$ filename=$(tr "/" "\n" <<< $fspec | tail -1)
$ echo $filename
abc.txt
The benefit of the "here string" is that it avoids the need/overhead of running an echo
command. In other words, the "here string" is internal to the shell. That is:
$ tr <<< $fspec
as opposed to:
$ echo $fspec | tr
If the XML output requirement can be changed you can always use binary serialization - which is better suited for working with heterogeneous lists of objects. Here's an example:
private void SerializeList(List<Object> Targets, string TargetPath)
{
IFormatter Formatter = new BinaryFormatter();
using (FileStream OutputStream = System.IO.File.Create(TargetPath))
{
try
{
Formatter.Serialize(OutputStream, Targets);
} catch (SerializationException ex) {
//(Likely Failed to Mark Type as Serializable)
//...
}
}
Use as such:
[Serializable]
public class Animal
{
public string Home { get; set; }
}
[Serializable]
public class Person
{
public string Name { get; set; }
}
public void ExampleUsage() {
List<Object> SerializeMeBaby = new List<Object> {
new Animal { Home = "London, UK" },
new Person { Name = "Skittles" }
};
string TargetPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Test1.dat");
SerializeList(SerializeMeBaby, TargetPath);
}
You don't need to escape it inside. You can use the |
character to delimit searches.
"\"foo\"\'bar\'".replace(/("|')/g, "")
Some applications launches themselves by protocols. like itunes with "itms://" links. I don't know however how you can register that with windows.
For some time I was really annoyed by the fact that matplotlib doesn't generate colormaps with random colors, as this is a common need for segmentation and clustering tasks.
By just generating random colors we may end with some that are too bright or too dark, making visualization difficult. Also, usually we need the first or last color to be black, representing the background or outliers. So I've wrote a small function for my everyday work
Here's the behavior of it:
new_cmap = rand_cmap(100, type='bright', first_color_black=True, last_color_black=False, verbose=True)
Than you just use new_cmap as your colormap on matplotlib:
ax.scatter(X,Y, c=label, cmap=new_cmap, vmin=0, vmax=num_labels)
The code is here:
def rand_cmap(nlabels, type='bright', first_color_black=True, last_color_black=False, verbose=True):
"""
Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks
:param nlabels: Number of labels (size of colormap)
:param type: 'bright' for strong colors, 'soft' for pastel colors
:param first_color_black: Option to use first color as black, True or False
:param last_color_black: Option to use last color as black, True or False
:param verbose: Prints the number of labels and shows the colormap. True or False
:return: colormap for matplotlib
"""
from matplotlib.colors import LinearSegmentedColormap
import colorsys
import numpy as np
if type not in ('bright', 'soft'):
print ('Please choose "bright" or "soft" for type')
return
if verbose:
print('Number of labels: ' + str(nlabels))
# Generate color map for bright colors, based on hsv
if type == 'bright':
randHSVcolors = [(np.random.uniform(low=0.0, high=1),
np.random.uniform(low=0.2, high=1),
np.random.uniform(low=0.9, high=1)) for i in xrange(nlabels)]
# Convert HSV list to RGB
randRGBcolors = []
for HSVcolor in randHSVcolors:
randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2]))
if first_color_black:
randRGBcolors[0] = [0, 0, 0]
if last_color_black:
randRGBcolors[-1] = [0, 0, 0]
random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
# Generate soft pastel colors, by limiting the RGB spectrum
if type == 'soft':
low = 0.6
high = 0.95
randRGBcolors = [(np.random.uniform(low=low, high=high),
np.random.uniform(low=low, high=high),
np.random.uniform(low=low, high=high)) for i in xrange(nlabels)]
if first_color_black:
randRGBcolors[0] = [0, 0, 0]
if last_color_black:
randRGBcolors[-1] = [0, 0, 0]
random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
# Display colorbar
if verbose:
from matplotlib import colors, colorbar
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1, figsize=(15, 0.5))
bounds = np.linspace(0, nlabels, nlabels + 1)
norm = colors.BoundaryNorm(bounds, nlabels)
cb = colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None,
boundaries=bounds, format='%1i', orientation=u'horizontal')
return random_colormap
It's also on github: https://github.com/delestro/rand_cmap
ScheduledThreadPoolExecutor
has this ability, but it's quite heavyweight.
Timer
also has this ability but opens several thread even if used only once.
Here's a simple implementation with a test (signature close to Android's Handler.postDelayed()):
public class JavaUtil {
public static void postDelayed(final Runnable runnable, final long delayMillis) {
final long requested = System.currentTimeMillis();
new Thread(new Runnable() {
@Override
public void run() {
// The while is just to ignore interruption.
while (true) {
try {
long leftToSleep = requested + delayMillis - System.currentTimeMillis();
if (leftToSleep > 0) {
Thread.sleep(leftToSleep);
}
break;
} catch (InterruptedException ignored) {
}
}
runnable.run();
}
}).start();
}
}
Test:
@Test
public void testRunsOnlyOnce() throws InterruptedException {
long delay = 100;
int num = 0;
final AtomicInteger numAtomic = new AtomicInteger(num);
JavaUtil.postDelayed(new Runnable() {
@Override
public void run() {
numAtomic.incrementAndGet();
}
}, delay);
Assert.assertEquals(num, numAtomic.get());
Thread.sleep(delay + 10);
Assert.assertEquals(num + 1, numAtomic.get());
Thread.sleep(delay * 2);
Assert.assertEquals(num + 1, numAtomic.get());
}
OK so, picture the scenario I was just in:
You attempt a merge
, or maybe a cherry-pick
, and you're stopped with
$ git cherry-pick 1023e24
error: could not apply 1023e24... [Commit Message]
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'
Now, you view the conflicted file and you really don't want to keep your changes. In my case above, the file was conflicted on just a newline my IDE had auto-added. To undo your changes and accept their's, the easiest way is:
git checkout --theirs path/to/the/conflicted_file.php
git add path/to/the/conflicted_file.php
The converse of this (to overwrite the incoming version with your version) is
git checkout --ours path/to/the/conflicted_file.php
git add path/to/the/conflicted_file.php
Surprisingly, I couldn't find this answer very easily on the Net.
In both cases your inner dimension may be dynamically specified (i.e. taken from a variable), but the difference is in the outer dimension.
This question is basically equivalent to the following:
Is
int* x = new int[4];
"better" thanint x[4]
?
The answer is: "no, unless you need to choose that array dimension dynamically."
Without using any API You can do something like this too by using pure CSS and Jquery Demo
HTML
<div class="pointer_tooltip">
Click & Drag to draw the area
</div>
CSS
.pointer_tooltip{
width : auto;
height : auto;
padding : 10px;
border-radius : 5px;
background-color : #fff;
position: absolute;
}
Jquery
$(document).mousemove(function( event ) {
var pageCoords = "( " + event.pageX + ", " + event.pageY + " )";
//set the actuall width
$('.pointer_tooltip').width($('.pointer_tooltip').width());
var position_top = event.pageY+18;
var position_left = event.pageX-60;
var width=$('body').width()-$('.pointer_tooltip').width();
//check if left not minus
if(position_left<0){
position_left=10;
}else if(position_left > width){
position_left=width-10;
}
$('.pointer_tooltip').css('top',position_top+'px');
$('.pointer_tooltip').css('left',position_left+'px');
});
Update 2018...
card
has replaced the well
.
Bootstrap 4
<div class="card card-body bg-light">
Well
</div>
or, as two DIVs...
<div class="card bg-light">
<div class="card-body">
...
</div>
</div>
(Note: in Bootstrap 4 Alpha, these were known as card-block
instead of card-body
and bg-faded
instead of bg-light
)
You could try out the following code snippet:
private Point CenterOfMenuPanel<T>(T control, int height=0) where T:Control {
Point center = new Point(
MenuPanel.Size.Width / 2 - control.Width * 2,
height != 0 ? height : MenuPanel.Size.Height / 2 - control.Height / 2);
return center;
}
It's Really Center
Since Python 3.5, subprocess.run() is recommended over subprocess.check_output():
>>> int(subprocess.run(["pidof", "-s", "your_process"], stdout=subprocess.PIPE).stdout)
Also, since Python 3.7, you can use the capture_output=true
parameter to capture stdout and stderr:
>>> int(subprocess.run(["pidof", "-s", "your process"], capture_output=True).stdout)
At my previous employer, we used custom HTML tags all the time to hold info about the form elements. The catch: We knew that the user was forced to use IE.
It didn't work well for FireFox at the time. I don't know if FireFox has changed this or not, but be aware that adding your own attributes to HTML elements may or may-not be supported by your reader's browser.
If you can control which browser your reader is using (i.e. an internal web applet for a corporation), then by all means, try it. What can it hurt, right?
This is the solution I use:
function resolve(path, obj=self, separator='.') {
var properties = Array.isArray(path) ? path : path.split(separator)
return properties.reduce((prev, curr) => prev && prev[curr], obj)
}
Example usage:
// accessing property path on global scope
resolve("document.body.style.width")
// or
resolve("style.width", document.body)
// accessing array indexes
// (someObject has been defined in the question)
resolve("part3.0.size", someObject) // returns '10'
// accessing non-existent properties
// returns undefined when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})
// accessing properties with unusual keys by changing the separator
var obj = { object: { 'a.property.name.with.periods': 42 } }
resolve('object->a.property.name.with.periods', obj, '->') // returns 42
// accessing properties with unusual keys by passing a property name array
resolve(['object', 'a.property.name.with.periods'], obj) // returns 42
Limitations:
[]
) for array indices—though specifying array indices between the separator token (e.g., .
) works fine as shown above. Instead use window.open()
:
The syntax is:
window.open(strUrl, strWindowName[, strWindowFeatures]);
Your code should have:
window.open('Prosjektplan.pdf');
Your code should be:
<p class="downloadBoks"
onclick="window.open('Prosjektplan.pdf')">Prosjektbeskrivelse</p>
Set the label's textAlignment
property to NSTextAlignmentRight
and augment its width.
Question 1:
vectorOfGamers.push_back(Player)
This is problematic because you cannot directly push a class name into a vector. You can either push an object of class into the vector or push reference or pointer to class type into the vector. For example:
vectorOfGamers.push_back(Player(name, id))
//^^assuming name and id are parameters to the vector, call Player constructor
//^^In other words, push `instance` of Player class into vector
Question 2:
These 3 classes derives from Gamer. Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that?
Yes you can. You can create a vector of pointers that points to the base class Gamer
.
A good choice is to use a vector of smart_pointer
, therefore, you do not need to manage pointer memory by yourself. Since the other three classes are derived from Gamer
, based on polymorphism, you can assign derived class objects to base class pointers. You may find more information from this post: std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?
json_encode works only with UTF-8 data. You'll have to ensure that your data is in UTF-8. alternatively, you can use iconv() to convert your results to UTF-8 before feeding them to json_encode()
I was getting this error, when I was using the same variable for json string and parsed json:
var json = '{"1":{"url":"somesite1","poster":"1.png","title":"site title"},"2":{"url":"somesite2","poster":"2.jpg","title":"site 2 title"}}'
function usingjson(){
var json = JSON.parse(json);
}
I changed function to:
function usingjson(){
var j = JSON.parse(json);
}
Now this error went away.
To diagnose this error quickly drop to a terminal or use the terminal built into Android Studio (accessible on in bottom status bar). Change to the main directory for your PROJECT (where settings.gradle
is located).
1.) Check to make sure your settings.gradle
includes the subproject. Something like this. This ensures your multi-project build knows about your library sub-project.
include ':apps:App1', ':apps:App2', ':library:Lib1'
Where the text between the colons are sub-directories.
2.) Run the following gradle command just see if Gradle can give you a list of tasks for the library. Use the same qualifier in the settings.gradle
definition. This will uncover issues with the Library build script in isolation.
./gradlew :library:Lib1:tasks --info
3.) Make sure the output from the last step listed an "assembleDefault" task. If it didn't make sure the Library is including the Android Library plugin in build.gradle
. Like this at the very top.
apply plugin: 'com.android.library'
I know the original poster's question was answered but I believe the answer has evolved over the past year and I think there are multiple reasons for the error. I think this resolution flow should assist those who run into the various issues.
Soon most computers will be 64-bit architectures with 64-bit OS:es running programs operating on containers of billions of elements. Then you must use size_t
instead of int
as loop index, otherwise your index will wrap around at the 2^32:th element, on both 32- and 64-bit systems.
Prepare for the future!
The keys are not shuffled or renumbered. The unset()
key is simply removed and the others remain.
$a = array(1,2,3,4,5);
unset($a[2]);
print_r($a);
Array
(
[0] => 1
[1] => 2
[3] => 4
[4] => 5
)
No it's not always wrong. If your loop condition is "while we haven't tried to read past end of file" then you use while (!feof(f))
. This is however not a common loop condition - usually you want to test for something else (such as "can I read more"). while (!feof(f))
isn't wrong, it's just used wrong.
As mainframer said, you can use grep, but i would use exit status for testing, try this:
#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"
echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found
if [ $? = 1 ]
then
echo "$anotherstring was not found"
fi
This could be a permissions issue.
I had the same issue recently. As a test, I created a simple hello.html page. When I tried loading it, I got an error message regarding permissions. Once I fixed the permissions issue in the root web folder, both the html page and the MVC rendering issues were resolved.
Using logging.basicConfig
, the following example works for me:
logging.basicConfig(
filename='HISTORYlistener.log',
level=logging.DEBUG,
format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
)
This allows you to format & config all in one line. A resulting log record looks as follows:
2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start
Uninstall Java (via Control Panel / Programs and Features)
Install Java JRE 7 --> OFFLINE <--
Configure JAVA_HOME and Path = %JAVA_HOME%/bin;%PATH%
I created the following Contains function using reflect package. This function can be used for various types like int32 or struct etc.
// Contains returns true if an element is present in a slice
func Contains(list interface{}, elem interface{}) bool {
listV := reflect.ValueOf(list)
if listV.Kind() == reflect.Slice {
for i := 0; i < listV.Len(); i++ {
item := listV.Index(i).Interface()
target := reflect.ValueOf(elem).Convert(reflect.TypeOf(item)).Interface()
if ok := reflect.DeepEqual(item, target); ok {
return true
}
}
}
return false
}
Usage of contains function is below
// slice of int32
containsInt32 := Contains([]int32{1, 2, 3, 4, 5}, 3)
fmt.Println("contains int32:", containsInt32)
// slice of float64
containsFloat64 := Contains([]float64{1.1, 2.2, 3.3, 4.4, 5.5}, 4.4)
fmt.Println("contains float64:", containsFloat64)
// slice of struct
type item struct {
ID string
Name string
}
list := []item{
item{
ID: "1",
Name: "test1",
},
item{
ID: "2",
Name: "test2",
},
item{
ID: "3",
Name: "test3",
},
}
target := item{
ID: "2",
Name: "test2",
}
containsStruct := Contains(list, target)
fmt.Println("contains struct:", containsStruct)
// Output:
// contains int32: true
// contains float64: true
// contains struct: true
Please see here for more details: https://github.com/glassonion1/xgo/blob/main/contains.go
For "English locale" file names, this works nicely. I'm using this for sanitizing uploaded file names. The file name is not meant to be linked to anything on disk, it's for when the file is being downloaded hence there are no path checks.
$file_name = preg_replace('/([^\x20-~]+)|([\\/:?"<>|]+)/g', '_', $client_specified_file_name);
Basically it strips all non-printable and reserved characters for Windows and other OSs. You can easily extend the pattern to support other locales and functionalities.
^[^<>]+$
The caret in the character class ([^
) means match anything but, so this means, beginning of string, then one or more of anything except <
and >
, then the end of the string.
The other answers are correct (with a caveat*). I add this answer simply to show an example usage:
- (void)getYourAffairsInOrder
{
NSDate* methodStart = [NSDate date]; // Capture start time.
// … Do some work …
NSLog(@"DEBUG Method %s ran. Elapsed: %f seconds.", __func__, -([methodStart timeIntervalSinceNow])); // Calculate and report elapsed time.
}
On the debugger console, you see something like this:
DEBUG Method '-[XMAppDelegate getYourAffairsInOrder]' ran. Elapsed: 0.033827 seconds.
*Caveat: As others mentioned, use NSDate
to calculate elapsed time only for casual purposes. One such purpose might be common testing, crude profiling, where you just want a rough idea of how long a method is taking.
The risk is that the device's clock's current time setting could change at any moment because of network clock syncing. So NSDate
time could jump forward or backward at any moment.
Go with the mouse to the Windows Icon (lower left) and start typing "Anaconda". There should show up some matching entries. Select "Anaconda Prompt". A new command window, named "Anaconda Prompt" will open. Now, you can work from there with Python, conda and other tools.
I have also ran into this error when the package in one of my class files was incorrectly spelled. Many of these answers immediately jump to the Jar files but I would also check to make sure your packages are spelled correctly.
The name of the spyder executable was changed to spyder3.exe in python version 3. I install pyqt5 and spyder via pip and was able to launch spyder3. I first tried without installing pyqt5 and nothing happened. Once I installed pyqt5, then spyder 3 opened.
Try the following from a windows cmd.exe prompt:
C:\Users\..>pip install pyqt5
C:\Users\..>pip install spyder
C:\Users\..>spyder3
I have looked thorugh all of the anwers and was not quite satasifed. I found much easier and faster solution. Wanted to share for future readers.
View
inside your single recycler item. View
(Make sure you cast to appropirate ViewGroup
)onClickListener
to this parent. Sample code (It is written inside your onBindViewHolder
method of your adapter
):
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
ConstraintLayout parent = (ConstraintLayout) holder.title.getParent();
parent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "Clicked recycler view item at position " + position, Toast.LENGTH_SHORT).show();
}
});
}
If you'd like a string
> (1.7289).ToString("#.##")
"1.73"
Or a decimal
> Math.Round((Decimal)x, 2)
1.73m
But remember! Rounding is not distributive, ie. round(x*y) != round(x) * round(y)
. So don't do any rounding until the very end of a calculation, else you'll lose accuracy.
/* Microsoft Edge Browser 12-18 (All versions before Chromium) */
This one should work:
@supports (-ms-ime-align:auto) {
.selector {
property: value;
}
}
For more see: Browser Strangeness
>>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN])
>>> s[~s.isnull()]
0 1
1 2
2 3
3 4
5 5
update or even better approach as @DSM suggested in comments, using pandas.Series.dropna()
:
>>> s.dropna()
0 1
1 2
2 3
3 4
5 5
If last versions means last tag, and current versions means HEAD (current state), it's just a diff with the last tag:
Looking for tags:
$ git tag --list
...
v20.11.23.4
v20.11.25.1
v20.11.25.2
v20.11.25.351
The last tag would be:
$ git tag --list | tail -n 1
v20.11.25.351
Putting it together:
tag=$(git tag --list | tail -n 1)
git diff $tag
No there isn't, but you can check out indexOf as a starting point to developing your own, and/or look into regular expressions. It would be a good idea to familiarise yourself with the JavaScript string functions.
EDIT: This has been answered before:
As of PHP 7.4, this is no longer an issue. Support for caching_sha2
authentication method has been added to mysqlnd.
Currently, PHP mysqli extension do not support new caching_sha2 authentication feature. You have to wait until they release an update.
Check related post from MySQL developers: https://mysqlserverteam.com/upgrading-to-mysql-8-0-default-authentication-plugin-considerations/
They didn't mention PDO, maybe you should try to connect with PDO.
You can try this. :) simple solution!
=IF(ISNUMBER(MATCH(I1,E:E,0)),"TRUE","")
You can use a logging framework like loguru
since it includes timestamps and total uptime which can be used nicely for profiling:
Another dplyr
alternative with slice
where we repeat each row number freq
times
library(dplyr)
df %>%
slice(rep(seq_len(n()), freq)) %>%
select(-freq)
# var1 var2
#1 a d
#2 b e
#3 b e
#4 c f
#5 c f
#6 c f
seq_len(n())
part can be replaced with any of the following.
df %>% slice(rep(1:nrow(df), freq)) %>% select(-freq)
#Or
df %>% slice(rep(row_number(), freq)) %>% select(-freq)
#Or
df %>% slice(rep(seq_len(nrow(.)), freq)) %>% select(-freq)
I faced this issue when moved from Android 7(Nougat) to Android 8(Oreo).
I have tried several ways listed above and to my bad luck nothing worked.
So i changed the .apk file to .zip file extracted it and found lib folder with which this file was there /x86_64/darwin/libscrypt.dylib so to remove this i added a code in my build.gradle module below android section (i.e.)
packagingOptions {
exclude 'lib/x86_64/darwin/libscrypt.dylib'
exclude 'lib/x86_64/freebsd/libscrypt.so'
exclude 'lib/x86_64/linux/libscrypt.so'
}
Cheers issue solved
A decent implementation can be found at http://code.google.com/p/reallysimplehistory/. The only (but also) problem and bug it has is: in Internet Explorer modifying the location hash manually will reset the entire history stack (this is a browser issue and it cannot be solved).
Note, Internet Explorer 8 does have support for the "hashchange" event, and since it is becoming part of HTML5 you may expect other browsers to catch up.
Post::create([
'title' => request('title'),
'body' => request('body'),
'user_id' => auth()->id()
]);
you dont need the request() as you doing that already pulling the value of body and title
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
Yes you can. Since you are using spring, check out @PropertySource
anotation.
Anotate your configuration with
@PropertySource("application-${spring.profiles.active}.properties")
You can call it what ever you like, and add inn multiple property files if you like too. Can be nice if you have more sets and/or defaults that belongs to all environments (can be written with @PropertySource{...,...,...} as well).
@PropertySources({
@PropertySource("application-${spring.profiles.active}.properties"),
@PropertySource("my-special-${spring.profiles.active}.properties"),
@PropertySource("overridden.properties")})
Then you can start the application with environment
-Dspring.active.profiles=test
In this example, name will be replaced with application-test-properties and so on.
SELECT RTRIM(' Author ') AS Name;
Output will be without any trailing spaces.
Name —————— ‘ Author’
My best solution
function getBrowserInfo() {
const ua = navigator.userAgent; let tem;
let M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return { name: 'IE ', version: (tem[1] || '') };
}
if (M[1] === 'Chrome') {
tem = ua.match(/\bOPR\/(\d+)/);
if (tem != null) {
return { name: 'Opera', version: tem[1] };
}
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
tem = ua.match(/version\/(\d+)/i);
if (tem != null) {
M.splice(1, 1, tem[1]);
}
return {
name: M[0],
version: M[1],
};
}
getBrowserInfo();
In both: Anaconda prompt and the old cmd.exe, you change your directory by first changing to the drive you want, by simply writing its name followed by a ':
', exe: F:
, which will take you to the drive named 'F' on your machine. Then using the command cd
to navigate your way inside that drive as you normally would.
If you have the program and the core file, you can do the following steps.
1) Run the gdb on the program along with core file
$gdb ./test core
2) type info files and see what different segments are there in the core file.
(gdb)info files
A sample output:
(gdb)info files
Symbols from "/home/emntech/debugging/test".
Local core dump file:
`/home/emntech/debugging/core', file type elf32-i386.
0x0055f000 - 0x0055f000 is load1
0x0057b000 - 0x0057c000 is load2
0x0057c000 - 0x0057d000 is load3
0x00746000 - 0x00747000 is load4
0x00c86000 - 0x00c86000 is load5
0x00de0000 - 0x00de0000 is load6
0x00de1000 - 0x00de3000 is load7
0x00de3000 - 0x00de4000 is load8
0x00de4000 - 0x00de7000 is load9
0x08048000 - 0x08048000 is load10
0x08049000 - 0x0804a000 is load11
0x0804a000 - 0x0804b000 is load12
0xb77b9000 - 0xb77ba000 is load13
0xb77cc000 - 0xb77ce000 is load14
0xbf91d000 - 0xbf93f000 is load15
In my case I have 15 segments. Each segment has start of the address and end of the address. Choose any segment to search data for. For example lets select load11 and search for a pattern. Load11 has start address 0x08049000 and ends at 0x804a000.
3) Search for a pattern in the segment.
(gdb) find /w 0x08049000 0x0804a000 0x8048034
0x804903c
0x8049040
2 patterns found
If you don't have executable file you need to use a program which prints data of all segments of a core file. Then you can search for a particular data at an address. I don't find any program as such, you can use the program at the following link which prints data of all segments of a core or an executable file.
http://emntech.com/programs/printseg.c
Use Visual Studio Setup project. Setup project can automatically include .NET framework setup in your installation package:
Here is my step-by-step for windows forms application:
Create setup project. You can use Setup Wizard.
Select project type.
Select output.
Hit Finish.
Open setup project properties.
Chose to include .NET framework.
Build setup project
Check output
Note: The Visual Studio Installer projects are no longer pre-packed with Visual Studio. However, in Visual Studio 2013 you can download them by using:
Tools > Extensions and Updates > Online (search) > Visual Studio Installer Projects
in devices which has Android 4.3 and above you should follow these steps:
How to enable Developer Options:
Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.
In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.
This is the most complicated scenario I can imagine: I have a PDF file created with Ilustrator and modified with Acrobat to have AcroFields (AcroForm) that I'm going to fill with data with this Java code, the result of that PDF file with the data in the fields is modified adding a Document.
Actually in this case I'm dynamically generating a background that is added to a PDF that is also dynamically generated with a Document with an unknown amount of data or pages.
I'm using JBoss and this code is inside a JSP file (should work in any JSP webserver).
Note: if you are using IExplorer you must submit a HTTP form with POST method to be able to download the file. If not you are going to see the PDF code in the screen. This does not happen in Chrome or Firefox.
<%@ page import="java.io.*, com.lowagie.text.*, com.lowagie.text.pdf.*" %><%
response.setContentType("application/download");
response.setHeader("Content-disposition","attachment;filename=listaPrecios.pdf" );
// -------- FIRST THE PDF WITH THE INFO ----------
String str = "";
// lots of words
for(int i = 0; i < 800; i++) str += "Hello" + i + " ";
// the document
Document doc = new Document( PageSize.A4, 25, 25, 200, 70 );
ByteArrayOutputStream streamDoc = new ByteArrayOutputStream();
PdfWriter.getInstance( doc, streamDoc );
// lets start filling with info
doc.open();
doc.add(new Paragraph(str));
doc.close();
// the beauty of this is the PDF will have all the pages it needs
PdfReader frente = new PdfReader(streamDoc.toByteArray());
PdfStamper stamperDoc = new PdfStamper( frente, response.getOutputStream());
// -------- THE BACKGROUND PDF FILE -------
// in JBoss the file has to be in webinf/classes to be readed this way
PdfReader fondo = new PdfReader("listaPrecios.pdf");
ByteArrayOutputStream streamFondo = new ByteArrayOutputStream();
PdfStamper stamperFondo = new PdfStamper( fondo, streamFondo);
// the acroform
AcroFields form = stamperFondo.getAcroFields();
// the fields
form.setField("nombre","Avicultura");
form.setField("descripcion","Esto describe para que sirve la lista ");
stamperFondo.setFormFlattening(true);
stamperFondo.close();
// our background is ready
PdfReader fondoEstampado = new PdfReader( streamFondo.toByteArray() );
// ---- ADDING THE BACKGROUND TO EACH DATA PAGE ---------
PdfImportedPage pagina = stamperDoc.getImportedPage(fondoEstampado,1);
int n = frente.getNumberOfPages();
PdfContentByte background;
for (int i = 1; i <= n; i++) {
background = stamperDoc.getUnderContent(i);
background.addTemplate(pagina, 0, 0);
}
// after this everithing will be written in response.getOutputStream()
stamperDoc.close();
%>
There is another solution much simpler, and solves your problem. It depends the amount of text you want to add.
// read the file
PdfReader fondo = new PdfReader("listaPrecios.pdf");
PdfStamper stamper = new PdfStamper( fondo, response.getOutputStream());
PdfContentByte content = stamper.getOverContent(1);
// add text
ColumnText ct = new ColumnText( content );
// this are the coordinates where you want to add text
// if the text does not fit inside it will be cropped
ct.setSimpleColumn(50,500,500,50);
ct.setText(new Phrase(str, titulo1));
ct.go();
Just add style="width:5% !important;"
to th and td
<ng-container matColumnDef="username">
<th style="width:5% !important;" mat-header-cell *matHeaderCellDef> Full Name </th>
<td style="width:5% !important;" mat-cell *matCellDef="let element"> {{element.username}} ( {{element.usertype}} )</td>
</ng-container>
This BFS-like solution is pretty straightforward. Simply jumps levels one-by-one.
def getHeight(self,root, method='links'):
c_node = root
cur_lvl_nodes = [root]
nxt_lvl_nodes = []
height = {'links': -1, 'nodes': 0}[method]
while(cur_lvl_nodes or nxt_lvl_nodes):
for c_node in cur_lvl_nodes:
for n_node in filter(lambda x: x is not None, [c_node.left, c_node.right]):
nxt_lvl_nodes.append(n_node)
cur_lvl_nodes = nxt_lvl_nodes
nxt_lvl_nodes = []
height += 1
return height
You need to compile the bibtex file.
Suppose you have article.tex
and article.bib
. You need to run:
latex article.tex
(this will generate a document with question marks in place of unknown references)bibtex article
(this will parse all the .bib files that were included in the article and generate metainformation regarding references)latex article.tex
(this will generate document with all the references in the correct places)latex article.tex
(just in case if adding references broke page numbering somewhere)Here is the very nice link which explains the storage of signed and unsigned INT in C -
http://answers.yahoo.com/question/index?qid=20090516032239AAzcX1O
Taken from this above article -
"process called two's complement is used to transform positive numbers into negative numbers. The side effect of this is that the most significant bit is used to tell the computer if the number is positive or negative. If the most significant bit is a 1, then the number is negative. If it's 0, the number is positive."
s = 'hi how are you'
l = list(map(lambda x: x,s.split()))
print(l)
Output: ['hi', 'how', 'are', 'you']
You can also set a global ignore pattern in SVN's configuration file.
You can use a join to do this
SELECT t1.* from myTable t1
LEFT OUTER JOIN myTable t2 on t2.ID=t1.ID AND t2.`Date` > t1.`Date`
WHERE t2.`Date` IS NULL;
Only rows which have the latest date for each ID with have a NULL join to t2.
@Sparr is right, but I guess you expected byte array like byte[]
in C#. It's the same solution as Sparr did but instead of HEX you expected int
presentation (range from 0 to 255) of each char
. You can do as follows:
$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog');
var_dump($byte_array); // $byte_array should be int[] which can be converted
// to byte[] in C# since values are range of 0 - 255
By using var_dump
you can see that elements are int
(not string
).
array(44) { [1]=> int(84) [2]=> int(104) [3]=> int(101) [4]=> int(32)
[5]=> int(113) [6]=> int(117) [7]=> int(105) [8]=> int(99) [9]=> int(107)
[10]=> int(32) [11]=> int(102) [12]=> int(111) [13]=> int(120) [14]=> int(32)
[15]=> int(106) [16]=> int(117) [17]=> int(109) [18]=> int(112) [19]=> int(101)
[20]=> int(100) [21]=> int(32) [22]=> int(111) [23]=> int(118) [24]=> int(101)
[25]=> int(114) [26]=> int(32) [27]=> int(116) [28]=> int(104) [29]=> int(101)
[30]=> int(32) [31]=> int(108) [32]=> int(97) [33]=> int(122) [34]=> int(121)
[35]=> int(32) [36]=> int(98) [37]=> int(114) [38]=> int(111) [39]=> int(119)
[40]=> int(110) [41]=> int(32) [42]=> int(100) [43]=> int(111) [44]=> int(103) }
Be careful: the output array is of 1-based index (as it was pointed out in the comment)
As JJ Stiff suggests, you can add your text to a span and then measure the offsetHeight of the span.
var d = document.createElement("span");
d.font = "20px arial";
d.textContent = "Hello world!";
document.body.appendChild(d);
var emHeight = d.offsetHeight;
document.body.removeChild(d);
As shown on HTML5Rocks
It should be $cmd
instead of $($cmd)
. Works fine with that on my box.
Edit: Your script works only for one-word commands, like ls. It will not work for "ls cpp". For this to work, replace cmd="$1"; $cmd
with "$@"
. And, do not run your script as command="some cmd"; safeRun command
, run it as safeRun some cmd
.
Also, when you have to debug your bash scripts, execute with '-x' flag. [bash -x s.sh].
my telepathic abilities are not particularly great, but here is what I think you want:
def merge(list_of_strings, indices):
list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices)
list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]]
return list_of_strings
I should note, since it might be not obvious, that it's not the same as what is proposed in other answers.
SciTE does that very well with a single keystroke. It is also able to detect the most probably current line ending of the file (in case of mixed lines) and to convert them.
No need to install, lightweight, it can be used as a tool even if you don't want to give up your favorite editor.
This can be done in 2 ways:
if (str.match(/abc|def/)) {
...
}
if (/abc|def/.test(str)) {
....
}
In the HTML I added a class of nav-link to the a tag of each navigation link.
$('.nav-link').click(
function () {
$('.navbar-collapse').removeClass('in');
}
);
You give 1 Dollar, it gives you a cheese burger. You give the String and it gives you the Tab. Use the GET method of HashMap to get what you want.
HashMap.get("String");
If you have a full DB dump:
PGPASSWORD="your_pass" psql -h "your_host" -U "your_user" -d "your_database" -f backup.sql
If you have schemas kept separately, however, that won't work. Then you'll need to disable triggers for data insertion, akin to pg_restore --disable-triggers
. You can then use this:
cat database_data_only.gzip | gunzip | PGPASSWORD="your_pass" psql -h "your_host" -U root "your_database" -c 'SET session_replication_role = replica;' -f /dev/stdin
On a side note, it is a very unfortunate downside of postgres, I think. The default way of creating a dump in pg_dump
is incompatible with pg_restore
. With some additional keys, however, it is. WTF?
That's the compiler that comes with Apple's XCode tools package. They've hacked on it a little, but basically it's just g++.
You can download XCode for free (well, mostly, you do have to sign up to become an ADC member, but that's free too) here: http://developer.apple.com/technology/xcode.html
Edit 2013-01-25: This answer was correct in 2010. It needs an update.
While XCode tools still has a command-line C++ compiler, In recent versions of OS X (I think 10.7 and later) have switched to clang/llvm (mostly because Apple wants all the benefits of Open Source without having to contribute back and clang is BSD licensed). Secondly, I think all you have to do to install XCode is to download it from the App store. I'm pretty sure it's free there.
So, in order to get g++ you'll have to use something like homebrew (seemingly the current way to install Open Source software on the Mac (though homebrew has a lot of caveats surrounding installing gcc using it)), fink (basically Debian's apt system for OS X/Darwin), or MacPorts (Basically, OpenBSDs ports system for OS X/Darwin) to get it.
Fink definitely has the right packages. On 2016-12-26, it had gcc 5 and gcc 6 packages.
I'm less familiar with how MacPorts works, though some initial cursory investigation indicates they have the relevant packages as well.
https://turbo.net/ offers a browser sandbox in which containerised virtual machines run browser sessions for you. I tried it with Safari on my Windows development machine and it seems to work very well.
josonify works..but if you intend to just pass an array without the 'results' key, you can use json library from python. The following conversion works for me..
import json
@app.route('/test/json')
def test_json():
list = [
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]
return json.dumps(list))
if((a.trim()=="")||(a=="")||(a==null))
{
//empty condition
}
else
{
//working condition
}
You don't have to use it using src attribute
Wrong way (The image won't fit the button)
android:src="@drawable/myimage"
Right way is to use background atttribute
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/skin" />
where skin is an xml
skin.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- <item android:drawable="@drawable/button_disabled" android:state_enabled="false"/> -->
<item android:drawable="@drawable/button_pressed" android:state_pressed="true"/>
<!-- <item android:drawable="@drawable/button_focused" android:state_focused="true"/> -->
<item android:drawable="@drawable/button_normal"/>
</selector>
using button_pressed.png and button_normal.png
This will also help you in creating your skinned button with 4 states of pressed , normal , disabled and focussed. Make sure to keep same sizes of all pngs
You can change directory using this command like : currently if you current working directoris c:\ drive the if you want to go to your D:\ drive then type this command
cd /d D:\
now your current working directory is D:\ drive so you want go to Java directory under Docs so type below command :
cd Docs\Java
note : d stands for drive
Don't forget about fragmentation. If you have a lot of traffic, your pools can be fragmented and even if you have several MB free, there could be no block larger than 4KB. Check size of largest free block with a query like:
select
'0 (<140)' BUCKET, KSMCHCLS, KSMCHIDX,
10*trunc(KSMCHSIZ/10) "From",
count(*) "Count" ,
max(KSMCHSIZ) "Biggest",
trunc(avg(KSMCHSIZ)) "AvgSize",
trunc(sum(KSMCHSIZ)) "Total"
from
x$ksmsp
where
KSMCHSIZ<140
and
KSMCHCLS='free'
group by
KSMCHCLS, KSMCHIDX, 10*trunc(KSMCHSIZ/10)
UNION ALL
select
'1 (140-267)' BUCKET,
KSMCHCLS,
KSMCHIDX,
20*trunc(KSMCHSIZ/20) ,
count(*) ,
max(KSMCHSIZ) ,
trunc(avg(KSMCHSIZ)) "AvgSize",
trunc(sum(KSMCHSIZ)) "Total"
from
x$ksmsp
where
KSMCHSIZ between 140 and 267
and
KSMCHCLS='free'
group by
KSMCHCLS, KSMCHIDX, 20*trunc(KSMCHSIZ/20)
UNION ALL
select
'2 (268-523)' BUCKET,
KSMCHCLS,
KSMCHIDX,
50*trunc(KSMCHSIZ/50) ,
count(*) ,
max(KSMCHSIZ) ,
trunc(avg(KSMCHSIZ)) "AvgSize",
trunc(sum(KSMCHSIZ)) "Total"
from
x$ksmsp
where
KSMCHSIZ between 268 and 523
and
KSMCHCLS='free'
group by
KSMCHCLS, KSMCHIDX, 50*trunc(KSMCHSIZ/50)
UNION ALL
select
'3-5 (524-4107)' BUCKET,
KSMCHCLS,
KSMCHIDX,
500*trunc(KSMCHSIZ/500) ,
count(*) ,
max(KSMCHSIZ) ,
trunc(avg(KSMCHSIZ)) "AvgSize",
trunc(sum(KSMCHSIZ)) "Total"
from
x$ksmsp
where
KSMCHSIZ between 524 and 4107
and
KSMCHCLS='free'
group by
KSMCHCLS, KSMCHIDX, 500*trunc(KSMCHSIZ/500)
UNION ALL
select
'6+ (4108+)' BUCKET,
KSMCHCLS,
KSMCHIDX,
1000*trunc(KSMCHSIZ/1000) ,
count(*) ,
max(KSMCHSIZ) ,
trunc(avg(KSMCHSIZ)) "AvgSize",
trunc(sum(KSMCHSIZ)) "Total"
from
x$ksmsp
where
KSMCHSIZ >= 4108
and
KSMCHCLS='free'
group by
KSMCHCLS, KSMCHIDX, 1000*trunc(KSMCHSIZ/1000);
If the folder is accessible from the browser (not outside the document root of your web server), then you just need to output links to the locations of those files. If they are outside the document root, you will need to have links, buttons, whatever, that point to a PHP script that handles getting the files from their location and streaming to the response.
It's not possible in CSS at the moment, unless you want to select a child or sibling element (trivial and described in other answers here).
For all other cases you'll need JavaScript. jQuery and frameworks like Angular can tackle this problem with relative ease.
[Edit]
With the new CSS (4) selector :has(), you'll be able to target parent elements/classes, making a CSS-Only solution viable in the near future!
First post :)
For the OP, kristof's solution will work, unless there are issues with massive data and transaction log balloon issues on big deletes. Also, even with tlog storage to spare, since deletes write to the tlog, the operation can take a VERY long time for tables with hundreds of millions of rows.
I use a series of cursors to truncate and reload large copies of one of our huge production databases frequently. The solution engineered accounts for multiple schemas, multiple foreign key columns, and best of all can be sproc'd out for use in SSIS.
It involves creation of three staging tables (real tables) to house the DROP, CREATE, and CHECK FK scripts, creation and insertion of those scripts into the tables, and then looping over the tables and executing them. The attached script is four parts: 1.) creation and storage of the scripts in the three staging (real) tables, 2.) execution of the drop FK scripts via a cursor one by one, 3.) Using sp_MSforeachtable to truncate all the tables in the database other than our three staging tables and 4.) execution of the create FK and check FK scripts at the end of your ETL SSIS package.
Run the script creation portion in an Execute SQL task in SSIS. Run the "execute Drop FK Scripts" portion in a second Execute SQL task. Put the truncation script in a third Execute SQL task, then perform whatever other ETL processes you need to do prior to attaching the CREATE and CHECK scripts in a final Execute SQL task (or two if desired) at the end of your control flow.
Storage of the scripts in real tables has proven invaluable when the re-application of the foreign keys fails as you can select * from sync_CreateFK, copy/paste into your query window, run them one at a time, and fix the data issues once you find ones that failed/are still failing to re-apply.
Do not re-run the script again if it fails without making sure that you re-apply all of the foreign keys/checks prior to doing so, or you will most likely lose some creation and check fk scripting as our staging tables are dropped and recreated prior to the creation of the scripts to execute.
----------------------------------------------------------------------------
1)
/*
Author: Denmach
DateCreated: 2014-04-23
Purpose: Generates SQL statements to DROP, ADD, and CHECK existing constraints for a
database. Stores scripts in tables on target database for execution. Executes
those stored scripts via independent cursors.
DateModified:
ModifiedBy
Comments: This will eliminate deletes and the T-log ballooning associated with it.
*/
DECLARE @schema_name SYSNAME;
DECLARE @table_name SYSNAME;
DECLARE @constraint_name SYSNAME;
DECLARE @constraint_object_id INT;
DECLARE @referenced_object_name SYSNAME;
DECLARE @is_disabled BIT;
DECLARE @is_not_for_replication BIT;
DECLARE @is_not_trusted BIT;
DECLARE @delete_referential_action TINYINT;
DECLARE @update_referential_action TINYINT;
DECLARE @tsql NVARCHAR(4000);
DECLARE @tsql2 NVARCHAR(4000);
DECLARE @fkCol SYSNAME;
DECLARE @pkCol SYSNAME;
DECLARE @col1 BIT;
DECLARE @action CHAR(6);
DECLARE @referenced_schema_name SYSNAME;
--------------------------------Generate scripts to drop all foreign keys in a database --------------------------------
IF OBJECT_ID('dbo.sync_dropFK') IS NOT NULL
DROP TABLE sync_dropFK
CREATE TABLE sync_dropFK
(
ID INT IDENTITY (1,1) NOT NULL
, Script NVARCHAR(4000)
)
DECLARE FKcursor CURSOR FOR
SELECT
OBJECT_SCHEMA_NAME(parent_object_id)
, OBJECT_NAME(parent_object_id)
, name
FROM
sys.foreign_keys WITH (NOLOCK)
ORDER BY
1,2;
OPEN FKcursor;
FETCH NEXT FROM FKcursor INTO
@schema_name
, @table_name
, @constraint_name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @tsql = 'ALTER TABLE '
+ QUOTENAME(@schema_name)
+ '.'
+ QUOTENAME(@table_name)
+ ' DROP CONSTRAINT '
+ QUOTENAME(@constraint_name)
+ ';';
--PRINT @tsql;
INSERT sync_dropFK (
Script
)
VALUES (
@tsql
)
FETCH NEXT FROM FKcursor INTO
@schema_name
, @table_name
, @constraint_name
;
END;
CLOSE FKcursor;
DEALLOCATE FKcursor;
---------------Generate scripts to create all existing foreign keys in a database --------------------------------
----------------------------------------------------------------------------------------------------------
IF OBJECT_ID('dbo.sync_createFK') IS NOT NULL
DROP TABLE sync_createFK
CREATE TABLE sync_createFK
(
ID INT IDENTITY (1,1) NOT NULL
, Script NVARCHAR(4000)
)
IF OBJECT_ID('dbo.sync_createCHECK') IS NOT NULL
DROP TABLE sync_createCHECK
CREATE TABLE sync_createCHECK
(
ID INT IDENTITY (1,1) NOT NULL
, Script NVARCHAR(4000)
)
DECLARE FKcursor CURSOR FOR
SELECT
OBJECT_SCHEMA_NAME(parent_object_id)
, OBJECT_NAME(parent_object_id)
, name
, OBJECT_NAME(referenced_object_id)
, OBJECT_ID
, is_disabled
, is_not_for_replication
, is_not_trusted
, delete_referential_action
, update_referential_action
, OBJECT_SCHEMA_NAME(referenced_object_id)
FROM
sys.foreign_keys WITH (NOLOCK)
ORDER BY
1,2;
OPEN FKcursor;
FETCH NEXT FROM FKcursor INTO
@schema_name
, @table_name
, @constraint_name
, @referenced_object_name
, @constraint_object_id
, @is_disabled
, @is_not_for_replication
, @is_not_trusted
, @delete_referential_action
, @update_referential_action
, @referenced_schema_name;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN
SET @tsql = 'ALTER TABLE '
+ QUOTENAME(@schema_name)
+ '.'
+ QUOTENAME(@table_name)
+ CASE
@is_not_trusted
WHEN 0 THEN ' WITH CHECK '
ELSE ' WITH NOCHECK '
END
+ ' ADD CONSTRAINT '
+ QUOTENAME(@constraint_name)
+ ' FOREIGN KEY (';
SET @tsql2 = '';
DECLARE ColumnCursor CURSOR FOR
SELECT
COL_NAME(fk.parent_object_id
, fkc.parent_column_id)
, COL_NAME(fk.referenced_object_id
, fkc.referenced_column_id)
FROM
sys.foreign_keys fk WITH (NOLOCK)
INNER JOIN sys.foreign_key_columns fkc WITH (NOLOCK) ON fk.[object_id] = fkc.constraint_object_id
WHERE
fkc.constraint_object_id = @constraint_object_id
ORDER BY
fkc.constraint_column_id;
OPEN ColumnCursor;
SET @col1 = 1;
FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@col1 = 1)
SET @col1 = 0;
ELSE
BEGIN
SET @tsql = @tsql + ',';
SET @tsql2 = @tsql2 + ',';
END;
SET @tsql = @tsql + QUOTENAME(@fkCol);
SET @tsql2 = @tsql2 + QUOTENAME(@pkCol);
--PRINT '@tsql = ' + @tsql
--PRINT '@tsql2 = ' + @tsql2
FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;
--PRINT 'FK Column ' + @fkCol
--PRINT 'PK Column ' + @pkCol
END;
CLOSE ColumnCursor;
DEALLOCATE ColumnCursor;
SET @tsql = @tsql + ' ) REFERENCES '
+ QUOTENAME(@referenced_schema_name)
+ '.'
+ QUOTENAME(@referenced_object_name)
+ ' ('
+ @tsql2 + ')';
SET @tsql = @tsql
+ ' ON UPDATE '
+
CASE @update_referential_action
WHEN 0 THEN 'NO ACTION '
WHEN 1 THEN 'CASCADE '
WHEN 2 THEN 'SET NULL '
ELSE 'SET DEFAULT '
END
+ ' ON DELETE '
+
CASE @delete_referential_action
WHEN 0 THEN 'NO ACTION '
WHEN 1 THEN 'CASCADE '
WHEN 2 THEN 'SET NULL '
ELSE 'SET DEFAULT '
END
+
CASE @is_not_for_replication
WHEN 1 THEN ' NOT FOR REPLICATION '
ELSE ''
END
+ ';';
END;
-- PRINT @tsql
INSERT sync_createFK
(
Script
)
VALUES (
@tsql
)
-------------------Generate CHECK CONSTRAINT scripts for a database ------------------------------
----------------------------------------------------------------------------------------------------------
BEGIN
SET @tsql = 'ALTER TABLE '
+ QUOTENAME(@schema_name)
+ '.'
+ QUOTENAME(@table_name)
+
CASE @is_disabled
WHEN 0 THEN ' CHECK '
ELSE ' NOCHECK '
END
+ 'CONSTRAINT '
+ QUOTENAME(@constraint_name)
+ ';';
--PRINT @tsql;
INSERT sync_createCHECK
(
Script
)
VALUES (
@tsql
)
END;
FETCH NEXT FROM FKcursor INTO
@schema_name
, @table_name
, @constraint_name
, @referenced_object_name
, @constraint_object_id
, @is_disabled
, @is_not_for_replication
, @is_not_trusted
, @delete_referential_action
, @update_referential_action
, @referenced_schema_name;
END;
CLOSE FKcursor;
DEALLOCATE FKcursor;
--SELECT * FROM sync_DropFK
--SELECT * FROM sync_CreateFK
--SELECT * FROM sync_CreateCHECK
---------------------------------------------------------------------------
2.)
-----------------------------------------------------------------------------------------------------------------
----------------------------execute Drop FK Scripts --------------------------------------------------
DECLARE @scriptD NVARCHAR(4000)
DECLARE DropFKCursor CURSOR FOR
SELECT Script
FROM sync_dropFK WITH (NOLOCK)
OPEN DropFKCursor
FETCH NEXT FROM DropFKCursor
INTO @scriptD
WHILE @@FETCH_STATUS = 0
BEGIN
--PRINT @scriptD
EXEC (@scriptD)
FETCH NEXT FROM DropFKCursor
INTO @scriptD
END
CLOSE DropFKCursor
DEALLOCATE DropFKCursor
--------------------------------------------------------------------------------
3.)
------------------------------------------------------------------------------------------------------------------
----------------------------Truncate all tables in the database other than our staging tables --------------------
------------------------------------------------------------------------------------------------------------------
EXEC sp_MSforeachtable 'IF OBJECT_ID(''?'') NOT IN
(
ISNULL(OBJECT_ID(''dbo.sync_createCHECK''),0),
ISNULL(OBJECT_ID(''dbo.sync_createFK''),0),
ISNULL(OBJECT_ID(''dbo.sync_dropFK''),0)
)
BEGIN TRY
TRUNCATE TABLE ?
END TRY
BEGIN CATCH
PRINT ''Truncation failed on''+ ? +''
END CATCH;'
GO
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
----------------------------execute Create FK Scripts and CHECK CONSTRAINT Scripts---------------
----------------------------tack me at the end of the ETL in a SQL task-------------------------
-------------------------------------------------------------------------------------------------
DECLARE @scriptC NVARCHAR(4000)
DECLARE CreateFKCursor CURSOR FOR
SELECT Script
FROM sync_createFK WITH (NOLOCK)
OPEN CreateFKCursor
FETCH NEXT FROM CreateFKCursor
INTO @scriptC
WHILE @@FETCH_STATUS = 0
BEGIN
--PRINT @scriptC
EXEC (@scriptC)
FETCH NEXT FROM CreateFKCursor
INTO @scriptC
END
CLOSE CreateFKCursor
DEALLOCATE CreateFKCursor
-------------------------------------------------------------------------------------------------
DECLARE @scriptCh NVARCHAR(4000)
DECLARE CreateCHECKCursor CURSOR FOR
SELECT Script
FROM sync_createCHECK WITH (NOLOCK)
OPEN CreateCHECKCursor
FETCH NEXT FROM CreateCHECKCursor
INTO @scriptCh
WHILE @@FETCH_STATUS = 0
BEGIN
--PRINT @scriptCh
EXEC (@scriptCh)
FETCH NEXT FROM CreateCHECKCursor
INTO @scriptCh
END
CLOSE CreateCHECKCursor
DEALLOCATE CreateCHECKCursor
I am using Google appengine java sdk and was facing similar issue. I had to add
<runtime>java8</runtime>
in appengine-web.xml file to make it work.
Chain selectors are not limited just to classes, you can do it for both classes and ids.
Classes
.classA.classB {
/*style here*/
}
Class & Id
.classA#idB {
/*style here*/
}
Id & Id
#idA#idB {
/*style here*/
}
All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".
For your case
li.left.ui-class-selector {
/*style here*/
}
or
.left.ui-class-selector {
/*style here*/
}
What's the first part of your Subversion repository URL?
I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.
If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.
The only way around that is to log into a local machine over the VPN, and then do everything from that system.
Yup, this is possible of course. Here are several examples.
-- one way to do this
DECLARE @Cnt int
SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn
-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)
-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double
SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable
You should use dict.items()
.
Here is a one liner solution for your problem:
[(k,v) for k,v in dict.items()]
and result:
[('Food', 'Fish&Chips'), ('2012', 'Olympics'), ('Capital', 'London')]
or you can do
l=[]
[l.extend([k,v]) for k,v in dict.items()]
for:
['Food', 'Fish&Chips', '2012', 'Olympics', 'Capital', 'London']
Just simply.. #sometime when larger table we can't add the id to each tr
<table>
<tr>
<td>some text</td>
<td>something</td>
</tr>
<tr>
<td>Hello</td>
<td>Hel</td>
</tr>
</table>
<script>
var cell = document.getElementsByTagName("td");
var i = 0;
while(cell[i] != undefined){
alert(cell[i].innerHTML); //do some alert for test
i++;
}//end while
</script>
I ran into the same problem. Placing a forward slash after the folder name worked for me.
ex: git add foldername/
Just an idea here: when it comes to radio inputs in React, I usually render all of them in a different way that was mentionned in the previous answers.
If this could help anyone who needs to render plenty of radio buttons:
import React from "react"_x000D_
import ReactDOM from "react-dom"_x000D_
_x000D_
// This Component should obviously be a class if you want it to work ;)_x000D_
_x000D_
const RadioInputs = (props) => {_x000D_
/*_x000D_
[[Label, associated value], ...]_x000D_
*/_x000D_
_x000D_
const inputs = [["Male", "M"], ["Female", "F"], ["Other", "O"]]_x000D_
_x000D_
return (_x000D_
<div>_x000D_
{_x000D_
inputs.map(([text, value], i) => (_x000D_
<div key={ i }>_x000D_
<input type="radio"_x000D_
checked={ this.state.gender === value } _x000D_
onChange={ /* You'll need an event function here */ } _x000D_
value={ value } /> _x000D_
{ text }_x000D_
</div>_x000D_
))_x000D_
}_x000D_
</div>_x000D_
)_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<RadioInputs />,_x000D_
document.getElementById("root")_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
exitcode = data.wait()
. The child process will be blocked If it writes to standard output/error, and/or reads from standard input, and there are no peers.
My two cents: In my case, cacerts was not a folder, but a file, and also it was presents on two paths After discover it, error disappeared after copy the .jks file over that file.
# locate cacerts
/usr/java/jdk1.8.0_221-amd64/jre/lib/security/cacerts
/usr/java/jre1.8.0_221-amd64/lib/security/cacerts
After backup them, I copy the .jks over.
cp /path_of_jks_file/file.jks /usr/java/jdk1.8.0_221-amd64/jre/lib/security/cacerts
cp /path_of_jks_file/file.jks /usr/java/jre1.8.0_221-amd64/lib/security/cacerts
Note: this basic trick resolves this error on a Genexus project, in spite file.jks is also on the server.xml file of the Tomcat.
I came across this as a regression bug when refactoring code from traditional using
blocks to the new C# 8.0 using declaration style, where the block ends when the variable falls out of scope at the end of the method.
Old style:
//...
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aesCrypto.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(rawCipherText, 0, rawCipherText.Length);
}
return Encoding.Unicode.GetString(ms.ToArray());
}
New, less indented style:
//...
using MemoryStream ms = new MemoryStream();
using CryptoStream cs = new CryptoStream(ms, aesCrypto.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(rawCipherText, 0, rawCipherText.Length);
cs.FlushFinalBlock();
return Encoding.Unicode.GetString(ms.ToArray());
With the old style, the using
block for the CryptoStream terminated and the finalizer was called before memory stream gets read in the return
statement, so the CryptoStream was automatically flushed.
With the new style, the memory stream is read before the CryptoStream finalizer gets called, so I had to manually call FlushFinalBlock()
before reading from the memory stream in order to fix this issue. I had to manually flush the final block for both the encrypt and the decrypt methods, when they were written in the new using
style.
Have you tried this?
$('.myClass, .myOtherClass').removeClass('theclass');
LANGUAGE INDEPENDENCY:
The Andrei Coscodan solution is language dependent, so a way to try to fix it is to reserve all the tags for each field: year, month and day on target languages. Consider Portugese and English, after the parsing do a final set as:
set Year=%yy%%aa%
set Month=%mm%
set Day=%dd%
Look for the year setting, I used both tags from English and Portuguese, it worked for me in Brazil where we have these two languages as the most common in Windows instalations. I expect this will work also for some languages with Latin origin like as French, Spanish, and so on.
Well, the full script could be:
@echo off
setlocal enabledelayedexpansion
:: Extract date fields - language dependent
for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (
set v1=%%i& set v2=%%j& set v3=%%k
if "%%i:~0,1%%" gtr "9" (set v1=%%j& set v2=%%k& set v3=%%l)
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo.^|date') do (
set %%m=!v1!& set %%n=!v2!& set %%o=!v3!
)
)
:: Final set for language independency (English and Portuguese - maybe works for Spanish and French)
set year=%yy%%aa%
set month=%mm%
set day=%dd%
:: Testing
echo Year:[%year%] - month:[%month%] - day:[%day%]
endlocal
pause
I hope this helps someone that deal with diferent languages.