HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
All requests get routed through default.aspx first - so assuming you can just pop in code behind there.
I solved the problem by adding an fake autocomplete name for all inputs.
$("input").attr("autocomplete", "fake-name-disable-autofill");
Try the command spyder3
If you check the scripts folder you'll find spyder3.exe
Try this, In your onCreate()
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
And for clickevent,
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
If you've used Advanced Installer
to build your .msi you will want to use APPDIR=
Try using an ImageList
ImageList imgList = new ImageList;
imgList.TransparentColor = Color.White;
Load the image like this:
picturebox.Image = imgList.Images[img_index];
For those doing video I cobbled the following based on @tsh :
import cv2 as cv
import numpy as np
def nothing(x):pass
cap = cv.VideoCapture(0)
cv.namedWindow('videoUI', cv.WINDOW_NORMAL)
cv.createTrackbar('T','videoUI',0,255,nothing)
while(True):
ret, frame = cap.read()
vid_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
thresh = cv.getTrackbarPos('T','videoUI');
vid_bw = cv.threshold(vid_gray, thresh, 255, cv.THRESH_BINARY)[1]
cv.imshow('videoUI',cv.flip(vid_bw,1))
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
Results in:
If you want the basic answer to have the files on the left-hand side, just go on "View" then "Tool Buttons", you will then be able to choose "project".
Use Pattern
package in Android to match the input validation for email and phone
Do like
android.util.Patterns.EMAIL_ADDRESS.matcher(input).matches();
android.util.Patterns.PHONE.matcher(input).matches();
You don't need to use array_push() function, you can assign new value with new key directly to the array like..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
I also had a similar problem like yours. The problem is that you are using an old php version. I have upgraded to PHP 5.6 and the problem no longer exist.
The <span>
tag will need to be set to display:block
as it is an inline element and will ignore width.
so:
<style type="text/css"> span { width: 50px; display: block; } </style>
and then:
<li><span> </span>something</li>
<li><span>AND</span>something else</li>
import java.util.Arrays;
class Soft{
public static void main(String[] args){
int[] nums=range(9, 12);
System.out.println(Arrays.toString(nums));
}
static int[] range(int low, int high){
int[] a=new int[high-low];
for(int i=0,j=low;i<high-low;i++,j++){
a[i]=j;
}
return a;
}
}
My code is similar to Python`s range :)
Late to the party on this question, but this is even easier:
$('#myForm').submit(function() {
// Get all the forms elements and their values in one step
var values = $(this).serialize();
});
I was recently shown this website for liquid layouts using CSS. http://matthewjamestaylor.com/blog/perfect-multi-column-liquid-layouts (Take a look at the demo pages in the links below).
The author now provides an example for fixed width layouts. Check out; http://matthewjamestaylor.com/blog/how-to-convert-a-liquid-layout-to-fixed-width.
This provides the following example(s), http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm (for two column layout like you are after I think)
http://matthewjamestaylor.com/blog/fixed-width-or-liquid-layout.htm (for three column layout).
Sorry for so many links to this guys site, but I think it is an AWESOME resource.
My few cents to previous excellent replies. the site www.sqlite.org works on a sqlite database. Here is the link when the author (Richard Hipp) replies to a similar question.
Try this one
where datediff(month, datetime_column, getdate()) <= 6
To exclude or filter out future dates
where datediff(month, datetime_column, getdate()) between 0 and 6
This part datediff(month, datetime_column, getdate())
will get the month difference in number of current date and Datetime_Column and will return Rows like:
Result
1
2
3
4
5
6
7
8
9
10
This is Our final condition to get last 6 months data
where result <= 6
Looking at Biju's answer I found a working solution.
I created an extra context-file test-context.xml
:
<context:property-placeholder location="classpath:config/spring-test.properties"/>
Containing the profile:
spring.profiles.active=localtest
And loading the test with:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration(locations = {
"classpath:config/test-context.xml" })
public class TestContext {
@Test
public void testContext(){
}
}
This saves some work when creating multiple test-cases.
XCODE 10 UPDATE
Click to Xcode at the Status Bar Then Select Preferences
In the PopUp Window Choose Locations before the last Segment
You can reach Derived Data folder with small right icon
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
To make my FFMPEG application I used this project (https://github.com/hiteshsondhi88/ffmpeg-android-java) so, I don't have to compile anything. I think it's the easy way to use FFMPEG in our Android applications.
More info on http://hiteshsondhi88.github.io/ffmpeg-android-java/
On some mobiles like mine (MIUI Redmi 3) you can just add specific Application on list where application doesnt stop when you terminate applactions in Task Manager (It will stop but it will start again)
Just go to Settings>PermissionsAutostart
I had this exact same problem. I fixed it by adding the following line to my FindOpenCV.cmake
file. Put it anywhere at the top before the rest of the code.
set (OpenCV_DIR /home/cmake/opencv/compiled) #change the path to match your complied directory of opencv
Basically you are telling FindOpenCV.cmake
where to find opencv files assuming the other compilation can find the FindOpenCV.cmake
There are method join
for string objects:
".".join(("a","b","c"))
Some time this problem occur due to incompatible java version and tomcat version.Choose the compatible version of both.
Use keypress
event on usersSearch
textbox and look for Enter button. If enter button is pressed then trigger the search button click event which will do the rest of work. Try this.
$('document').ready(function(){
$('#searchButton').click(function(){
var search = $('#usersSearch').val();
$.post('../searchusers.php',{search: search},function(response){
$('#userSearchResultsTable').html(response);
});
})
$('#usersSearch').keypress(function(e){
if(e.which == 13){//Enter key pressed
$('#searchButton').click();//Trigger search button click event
}
});
});
When you write in Visual Studio,
public ServiceTypesEnum Type { get; set; }
public string TypeString { get { return this.Type.ToString();}}
ReSharper will keep suggesting to convert it to:
public string TypeString => Type.ToString();
Extending DarenW's comment.
Once typename and class are not accepted to be very different, it might be still valid to be strict on their use. Use class only if is really a class, and typename when its a basic type, such as char.
These types are indeed also accepted instead of typename
template< char myc = '/' >
which would be in this case even superior to typename or class.
Think of "hintfullness" or intelligibility to other people. And actually consider that 3rd party software/scripts might try to use the code/information to guess what is happening with the template (consider swig).
No difference as such.
Convert.ToInt32()
calls int.Parse()
internally
Except for one thing Convert.ToInt32()
returns 0
when argument is null
Otherwise both work the same way
In my situation, I have a "model", consist of several String parameters, with the exception of one: it is byte array byte[]
.
Some code snippet:
String response = args[0].toString();
Gson gson = new Gson();
BaseModel responseModel = gson.fromJson(response, BaseModel.class);
The last line above is when the
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column
is triggered. Searching through the SO, I realised I need to have some form of Adapter
to convert my BaseModel
to and fro a JsonObject. Having mixed of String
and byte[]
in a model does complicate thing. Apparently, Gson
don't really like the situation.
I end up making an Adapter
to ensure byte[]
is converted to Base64
format. Here is my Adapter
class:
public class ByteArrayToBase64Adapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
@Override
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return Base64.decode(json.getAsString(), Base64.NO_WRAP);
}
@Override
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(Base64.encodeToString(src, Base64.NO_WRAP));
}
}
To convert JSONObject to model, I used the following:
Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64Adapter()).create();
BaseModel responseModel = customGson.fromJson(response, BaseModel.class);
Similarly, to convert the model to JSONObject, I used the following:
Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64Adapter()).create();
String responseJSon = customGson.toJson(response);
What the code is doing is basically to push the intended class/object
(in this case, byte[]
class) through the Adapter
whenever it is encountered during the convertion to/fro JSONObject.
Your best bet would be using the RFC defined mime-type audio/mpeg
.
What do you mean by "not always reliable"? If the system succeeds in setting your socket non non-blocking, it will be non-blocking. Socket operations will return EWOULDBLOCK
if they would block need to block (e.g. if the output buffer is full and you're calling send/write too often).
This forum thread has a few good points when working with non-blocking calls.
Use this instead:
string objTextBox = t.Text;
The object t
is the TextBox
. The object you call objTextBox
is assigned the ID
property of the TextBox
.
So better code would be:
TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;
Is this what you are after?
select * from tempdb..sysobjects
--for sql-server 2000 and later versions
select * from tempdb.sys.objects
--for sql-server 2005 and later versions
You can use
function renderGreeting(props: {Elem: React.Component<any, any>}) {
return <span>Hello, {props.Elem}!</span>;
}
However, does the following work?
function renderGreeting(Elem: React.ComponentType) {
const propsToPass = {one: 1, two: 2};
return <span>Hello, <Elem {...propsToPass} />!</span>;
}
See LINQ: How to get the latest/last record with a group by clause
var firstItemsInGroup = from b in mainButtons
group b by b.category into g
select g.First();
I assume that mainButtons are already sorted correctly.
If you need to specify custom sort order, use OrderBy override with Comparer.
var firstsByCompareInGroups = from p in rows
group p by p.ID into grp
select grp.OrderBy(a => a, new CompareRows()).First();
See an example in my post "Select First Row In Group using Custom Comparer"
If you have this issue with macOS, there is no easy way here: ( Especially, when you want to use R3.4. I have been there already.
R 3.4, rJava, macOS and even more mess
For R3.3 it's a little bit easier (R3.3 was compiled using different compiler).
A more extensive version of https://stackoverflow.com/a/10786066/1794894
/"([^"\\]{50,}(\\.[^"\\]*)*)"|\'[^\'\\]{50,}(\\.[^\'\\]*)*\'|“[^”\\]{50,}(\\.[^“\\]*)*”/
This version also contains
“
and close ”
)You can use .concat
method to create copy of your array with new data:
this.setState({ myArray: this.state.myArray.concat('new value') })
But beware of special behaviour of .concat
method when passing arrays - [1, 2].concat(['foo', 3], 'bar')
will result in [1, 2, 'foo', 3, 'bar']
.
Instead of
onClick="parent.location='http://www.facebook.com/'"
try using
onClick="window.open='http://www.facebook.com/'" onClick="window.open('http://www.facebook.com/','facebook')"
This will help for someone who is looking for a non technical answer
This is simple hack
Download the application App Share/Send Pro
from google play store. Select the app you want to send and method send application.
I usually use Bluetooth to send applications to my pc or another phone.
For what it's worth, it appears your intent is to use the incoming HTTP request to form another HTTP request. Sort of like a gateway. There is an excellent module django-revproxy that accomplishes exactly this.
The source is a pretty good reference on how to accomplish what you are trying to do.
I've just had this same issue with Ionic.
It turns out nothing was wrong with my code, I simply had to quit the ionic serve session and run ionic serve again.
After going back into the app, my states worked fine.
I would also suggest pressing save on your app.js file a few times if you are running gulp, to make sure everything gets re-compiled.
(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)
I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:
except Exception as e:
print(e)
will print the error output to sys.stdout
by default. A more appropriate approach to error handling in general would be:
except Exception as e:
print(e, file=sys.stderr)
(Note that you have to import sys
for this to work.) This way, the error is printed to STDERR
instead of STDOUT
, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.
I haven't used the traceback
module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.
You should check the EOF after reading from file.
fscanf_s // read from file
while(condition) // check EOF
{
fscanf_s // read from file
}
fd
Using fd
(alternative to find
), use the following syntax:
fd . foo -a
Where .
is the search pattern and foo
is the root directory.
E.g. to list all files in etc
recursively, run: fd . /etc -a
.
-a
,--absolute-path
Show absolute instead of relative paths
Depending on devices you might not find sqlite3 command in adb shell. In that case you might want to follow this :
adb shell
$ run-as package.name
$ cd ./databases/
$ ls -l #Find the current permissions - r=4, w=2, x=1
$ chmod 666 ./dbname.db
$ exit
$ exit
adb pull /data/data/package.name/databases/dbname.db ~/Desktop/
adb push ~/Desktop/dbname.db /data/data/package.name/databases/dbname.db
adb shell
$ run-as package.name
$ chmod 660 ./databases/dbname.db #Restore original permissions
$ exit
$ exit
for reference go to https://stackoverflow.com/a/17177091/3758972.
There might be cases when you get "remote object not found" after following above procedure. Then change permission of your database folder to 755 in adb shell.
$ chmod 755 databases/
But please mind that it'll work only on android version < 21.
The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
</head>
<body>
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: '100%',
videoId: 'osz5tVY97dQ',
playerVars: { 'autoplay': 1, 'playsinline': 1 },
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
event.target.playVideo();
}
</script>
</body>
</html>
I edited your plunker to include ABOS's solution.
<body ng-controller="MainCtrl">
<ul ng-repeat='item in items'>
<li ng-if='item.color'>The color is {{item.color}}</li>
<li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
</ul>
</body>
The latter alternative is used for methods on mocks that return void
.
Please have a look, for example, here: How to make mock to void methods with mockito
I had pip
referring by default to pip3, which made me download the libs for python3. On the contrary I launched the shell as python
(which opened python 2) and the library wasn't installed there obviously.
Once I matched the names pip3 -> python3, pip -> python (2) all worked.
This works from my Windows 10's cmd.exe prompt
powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"
This example shows
It's between the Z and the C on your keyboard.
I have no problem referring to enums directly in HTML, but in some cases there are cleaner alternatives that don't lose type-safe-ness. For instance if you choose the approach shown in my other answer, you may have declared TT in your component something like this:
public TT =
{
// Enum defines (Horizontal | Vertical)
FeatureBoxResponsiveLayout: FeatureBoxResponsiveLayout
}
To show a different layout in your HTML, you'd have an *ngIf
for each layout type, and you could refer directly to the enum in your component's HTML:
*ngIf="(featureBoxResponsiveService.layout | async) == TT.FeatureBoxResponsiveLayout.Horizontal"
This example uses a service to get the current layout, runs it through the async pipe and then compares it to our enum value. It's pretty verbose, convoluted and not much fun to look at. It also exposes the name of the enum, which itself may be overly verbose.
Alternatively you can do the following, and declare a more readable function in your component's .ts file :
*ngIf="isResponsiveLayout('Horizontal')"
Much cleaner! But what if someone types in 'Horziontal'
by mistake? The whole reason you wanted to use an enum in the HTML was to be typesafe right?
We can still achieve that with keyof and some typescript magic. This is the definition of the function:
isResponsiveLayout(value: keyof typeof FeatureBoxResponsiveLayout)
{
return FeatureBoxResponsiveLayout[value] == this.featureBoxResponsiveService.layout.value;
}
Note the usage of FeatureBoxResponsiveLayout[string]
which converts the string value passed in to the numeric value of the enum.
This will give an error message with an AOT compilation if you use an invalid value.
Argument of type '"H4orizontal"' is not assignable to parameter of type '"Vertical" | "Horizontal"
Currently VSCode isn't smart enough to underline H4orizontal
in the HTML editor, but you'll get the warning at compile time (with --prod build or --aot switch). This also may be improved upon in a future update.
This comment syntax should work for you:
@* enter comments here *@
sed
doesn't support \t
, nor other escape sequences like \n
for that matter. The only way I've found to do it was to actually insert the tab character in the script using sed
.
That said, you may want to consider using Perl or Python. Here's a short Python script I wrote that I use for all stream regex'ing:
#!/usr/bin/env python
import sys
import re
def main(args):
if len(args) < 2:
print >> sys.stderr, 'Usage: <search-pattern> <replace-expr>'
raise SystemExit
p = re.compile(args[0], re.MULTILINE | re.DOTALL)
s = sys.stdin.read()
print p.sub(args[1], s),
if __name__ == '__main__':
main(sys.argv[1:])
background: rgba(0,0,0,.5);
you can use rgba for opacity, will only work in ie9+ and better browsers
I wish the Lukas Olsen solution works for other scenarios, But in my case is quite different.
I faced the same while add ActionBarShelock to project, by comparing to the older library I found that application tag is missing in manifest. By adding one line I fixed my issue.
</application>
In case you are sending this post request to a cross domain, you should check out this link.
https://stackoverflow.com/a/1320708/969984
Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.
When you see an error with Uncaught (in promise)
This just means that you need to handle the promise with a .catch()
In this case, .play()
returns a promise. You can decide if you want to log a message, run some code, or do nothing, but as long as you have the .catch()
the error will go away.
var n = new Audio();
n.pause();
n.currentTime = 0;
n.play().catch(function(e) {
// console.log('There was an error', e);
});
You do not need to pass the size parameter, just declare Varchar
already understands that it is MAX like:
cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";
You will probably load the os module anyway, so another suggestion would be:
import os
myhost = os.uname()[1]
I apologize for resurecting this old thread, but I just wanted to let everyone know there is a very close Bootstrap like CSS framework specifically created for email styling, here is the link: http://zurb.com/ink/
Hope it helps someone.
Ninja edit: It has since been renamed to Foundation for Emails
and the new link is: https://foundation.zurb.com/emails.html
Silent but deadly edit: New link https://get.foundation/emails.html
You can use jQuery’s show()
and hide()
methods. Like below:
JQuery:
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var val = $(this).attr("value");
var target = $("." + val);
$(".msg").not(target).hide();
$(target).show();
});
});
HTML:
<input type="radio" name="color" value="yellow"> Yellow
<input type="radio" name="color" value="red"> Red
<input type="radio" name="color" value="green"> Green
<div class="yellow msg">You have selected Yellow</div>
<div class="red msg">You have selected Red</div>
<div class="green msg">You have selected Green</div>
Here is an example: Show/hide DIV based on Radio Button click
eof() checks the eofbit in the stream state.
On each read operation, if the position is at the end of stream and more data has to be read, eofbit is set to true. Therefore you're going to get an extra character before you get eofbit=1.
The correct way is to check whether the eof was reached (or, whether the read operation succeeded) after the reading operation. This is what your second version does - you do a read operation, and then use the resulting stream object reference (which >> returns) as a boolean value, which results in check for fail().
Found another solution for the same. It will be more helpful.
START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"
finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".
Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);
I had some lint errors in Android Studio that occurred only when I generated a signed APK.
To avoid it, I added the following to build.gradle
android {
lintOptions {
checkReleaseBuilds false
}
}
Android Text Justify For TextView XML
Simply android text-justify using in XML. You can simply implement in textview widget.
<TextView
android:justificationMode="inter_word"
/>
Default is android:justificationMode="none"
I have programmed an useful jQuery Plugin to create easily smart bubble popups with only a line of code in jQuery!
What You can do: - attach popups to any DOM element! - mouseover/mouseout events automatically managed! - set custom popups events! - create smart shadowed popups! (in IE too!) - choose popup’s style templates at runtime! - insert HTML messages inside popups! - set many options as: distances, velocity, delays, colors…
Popup’s shadows and colorized templates are fully supported by Internet Explorer 6+, Firefox, Opera 9+, Safari
You can download sources from http://plugins.jquery.com/project/jqBubblePopup
I looked at my Environment Variables and had a System Variable called _JAVA_OPTIONS
with the value -Xms256m -Xmx512m
, after changing this to -Xms256m -Xmx1024m
the max heap size increased accordingly.
If you have the same method name in two different classes and you just want to run one of them, this works:
pytest tests.py -k 'TestClassName and test_method_name'
function resizeWindow(){
var evt = document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false,window,0);
window.dispatchEvent(evt);
}
call this function after 500 milliseconds.
floor((day(@DateValue)-1)/7)+1
To convert the private key from PKCS#1 to PKCS#8 with openssl:
# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key
That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.
@if ($errors->has('category'))
<span class="error">{{ $errors->first('category') }}</span>
@endif
We have to differentiate here instead of blindly following general advice for specific cases.
Note that the following ignores the issue of containers of objects and what to do in the face of multiple d'tors of objects inside containers. (And it can be ignored partially, as some objects are just no good fit to put into a container.)
The whole problem becomes easier to think about when we split classes in two types. A class dtor can have two different responsibilities:
If we view the question this way, then I think that it can be argued that (R) semantics should never cause an exception from a dtor as there is a) nothing we can do about it and b) many free-resource operations do not even provide for error checking, e.g. void
free(void* p);
.
Objects with (C) semantics, like a file object that needs to successfully flush it's data or a ("scope guarded") database connection that does a commit in the dtor are of a different kind: We can do something about the error (on the application level) and we really should not continue as if nothing happened.
If we follow the RAII route and allow for objects that have (C) semantics in their d'tors I think we then also have to allow for the odd case where such d'tors can throw. It follows that you should not put such objects into containers and it also follows that the program can still terminate()
if a commit-dtor throws while another exception is active.
With regard to error handling (Commit / Rollback semantics) and exceptions, there is a good talk by one Andrei Alexandrescu: Error Handling in C++ / Declarative Control Flow (held at NDC 2014)
In the details, he explains how the Folly library implements an UncaughtExceptionCounter
for their ScopeGuard
tooling.
(I should note that others also had similar ideas.)
While the talk doesn't focus on throwing from a d'tor, it shows a tool that can be used today to get rid of the problems with when to throw from a d'tor.
In the future, there may be a std feature for this, see N3614, and a discussion about it.
Upd '17: The C++17 std feature for this is std::uncaught_exceptions
afaikt. I'll quickly quote the cppref article:
Notes
An example where
int
-returninguncaught_exceptions
is used is ... ... first creates a guard object and records the number of uncaught exceptions in its constructor. The output is performed by the guard object's destructor unless foo() throws (in which case the number of uncaught exceptions in the destructor is greater than what the constructor observed)
Ok I wonder when's the use but, here are two snipets you could use:
lastlog.cmd
@echo off
for /f "delims=" %%l in (log.txt) do set TimeStamp=%%l
echo %TimeStamp%
Change the "echo.." line, but the last log time is within %TimeStamp%. No temp files used, no clutter and reusable as it is in a variable.
On the other hand, if you need to know this WITHIN your code, and not from another batch, change your logging for:
set TimeStamp=%date%, %time%
echo %TimeStamp% >> log.txt
so that the variable %TimeStamp% is usable later when you need it.
control + '~' will work for toggling between the two. and '`' is just above the tab button. This shortcut only works in mac.
Many years ago, I invented (but never actually implemented) MiracleSort.
Start with an array in memory.
loop:
Check to see whether it's sorted.
Yes? We're done.
No? Wait a while and check again.
end loop
Eventually, alpha particles flipping bits in the memory chips should result in a successful sort.
For greater reliability, copy the array to a shielded location, and check potentially sorted arrays against the original.
So how do you check the potentially sorted array against the original? You just sort each array and check whether they match. MiracleSort is the obvious algorithm to use for this step.
EDIT: Strictly speaking, this is not an algorithm, since it's not guaranteed to terminate. Does "not an algorithm" qualify as "a worse algorithm"?
If your input is a character and the characters you are checking against are mostly consecutive you could try this:
if ((symbol >= 'A' && symbol <= 'Z') || symbol == '?') {
// ...
}
However if your input is a string a more compact approach (but slower) is to use a regular expression with a character class:
if (symbol.matches("[A-Z?]")) {
// ...
}
If you have a character you'll first need to convert it to a string before you can use a regular expression:
if (Character.toString(symbol).matches("[A-Z?]")) {
// ...
}
ul>li
selects all li
that are a direct child of ul
whereas ul li
selects all li
that are anywhere within (descending as deep as you like) a ul
For HTML:
<ul>
<li><span><a href='#'>Something</a></span></li>
<li><a href='#'>or Other</a></li>
</ul>
And CSS:
li a{ color: green; }
li>a{ color: red; }
The colour of Something
will remain green but or Other
will be red
Part 2, you should write the rule to be appropriate to the situation, I think the speed difference would be incredibly small, and probably overshadowed by the extra characters involved in writing more code, and definitely overshadowed by the time taken by the developer to think about it.
However, as a rule of thumb, the more specific you are with your rules, the faster the CSS engines can locate the DOM elements you want to apply it to, so I expect li>a
is faster than li a
as the DOM search can be cut short earlier. It also means that nested anchors are not styled with that rule, is that what you want? <~~ much more pertinent question.
Unicode arrows heads:
For ? and ? use ▲
and ▼
respectively if you cannot include Unicode characters directly (use UTF-8!).
Note that the font support for the smaller versions is not as good. Better to use the large versions in smaller font.
More Unicode arrows are at:
Lastly, these arrows are not ASCII, including ? and ?: they are Unicode.
This is a pretty old question, but perhaps this answer can still help someone else.
You can emulate a public constant that is restricted within a class scope by applying the final keyword to a method that returns a pre-defined value, like this:
class Foo {
// This is a private constant
final public MYCONSTANT()
{
return 'MYCONSTANT_VALUE';
}
}
The final keyword on a method prevents an extending class from re-defining the method. You can also place the final keyword in front of the class declaration, in which case the keyword prevents class Inheritance.
To get nearly exactly what Alex was looking for the following code can be used:
final class Constants {
public MYCONSTANT()
{
return 'MYCONSTANT_VALUE';
}
}
class Foo {
static public app()
{
return new Constants();
}
}
The emulated constant value would be accessible like this:
Foo::app()->MYCONSTANT();
Using the base
package:
df <- data.frame(days = c(88, 11, 2, 5, 22, 1, 222, 2), name = c("Lynn", "Tom", "Chris", "Lisa", "Kyla", "Tom", "Lynn", "Lynn"))
# Three lines
target <- c("Tom", "Lynn")
index <- df$name %in% target
df[index, ]
# One line
df[df$name %in% c("Tom", "Lynn"), ]
Output:
days name
1 88 Lynn
2 11 Tom
6 1 Tom
7 222 Lynn
8 2 Lynn
Using sqldf
:
library(sqldf)
# Two alternatives:
sqldf('SELECT *
FROM df
WHERE name = "Tom" OR name = "Lynn"')
sqldf('SELECT *
FROM df
WHERE name IN ("Tom", "Lynn")')
say easily http://www.google.com/maps/place/lat,lng
format
sample url:
Quick answer
On src, you can always specify files to ignore using "!".
Example (you want to exclude all *.min.js files on your js folder and subfolder:
gulp.src(['js/**/*.js', '!js/**/*.min.js'])
You can do it as well for individual files.
Expanded answer:
Extracted from gulp documentation:
gulp.src(globs[, options])
Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.
glob refers to node-glob syntax or it can be a direct file path.
So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.
On minimatch documentation, they point out the following:
if the pattern starts with a ! character, then it is negated.
And that is why using ! symbol will exclude files / directories from a gulp task
"The nature of math" regarding prime power moduli is that they are one building block of a finite field. The other two building blocks are an addition and a multiplication operation. The special property of prime moduli is that they form a finite field with the "regular" addition and multiplication operations, just taken to the modulus. This means every multiplication maps to a different integer modulo the prime, so does every addition.
Prime moduli are advantageous because:
They however have a big downside, they require an integer division, which takes many (~ 15-40) cycles, even on a modern CPU. With around half the computation one can make sure the hash is mixed up very well. Two multiplications and xorshift operations will mix better than a prime moudulus. Then we can use whatever hash table size and hash reduction is fastest, giving 7 operations in total for power of 2 table sizes and around 9 operations for arbitrary sizes.
I recently looked at many of the fastest hash table implementations and most of them don't use prime moduli.
The distribution of the hash table indices are mainly dependent on the hash function in use. A prime modulus can't fix a bad hash function and a good hash function does not benefit from a prime modulus. There are cases where they can be advantageous however. It can mend a half-bad hash function for example.
None of these answers fit my specific situation, which was that I wanted to run one specific cron job, just once, and run it immediately.
I'm on a Ubuntu server, and I use cPanel to setup my cron jobs.
I simply wrote down my current settings, and then edited them to be one minute from now. When I fixed another bug, I just edited it again to one minute from now. And when I was all done, I just reset the settings back to how they were before.
Example: It's 4:34pm right now, so I put 35 16 * * *, for it to run at 16:35.
It worked like a charm, and the most I ever had to wait was a little less than one minute.
I thought this was a better option than some of the other answers because I didn't want to run all of my weekly crons, and I didn't want the job to run every minute. It takes me a few minutes to fix whatever the issues were before I'm ready to test it again. Hopefully this helps someone.
This is my solution for this:
https://gist.github.com/BryanMoslo/808f7acb1dafcd049a1aebbeef8c2755
The element recibes a "tooltip-title" attribute with the tooltip text and it is displayed with CSS on hover, I prefer this solution because I don't have to include the tooltip text as a HTML element!
#HTML
<button class="tooltip" tooltip-title="Save">Hover over me</button>
#CSS
body{
padding: 50px;
}
.tooltip {
position: relative;
}
.tooltip:before {
content: attr(tooltip-title);
min-width: 54px;
background-color: #999999;
color: #fff;
font-size: 12px;
border-radius: 4px;
padding: 9px 0;
position: absolute;
top: -42px;
left: 50%;
margin-left: -27px;
visibility: hidden;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:after {
content: "";
position: absolute;
top: -9px;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #999999 transparent transparent;
visibility: hidden;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover:before,
.tooltip:hover:after{
visibility: visible;
opacity: 1;
}
Modifications are done to the new Slick version 1.7.1.
Here is a updated script example: jsfiddle
so it's easy)))
Watch this...
var stuff = {};
$('input[type=checkbox]').each(function(i, e) {
stuff[i] = e.checked;
});
And you will have:
Object {0: true, 1: false, 2: false, 3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff['row'+i] = e.checked;
});
You will have:
Object {row0: true, row1: false, row2: false, row3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff[e.className+i] = e.checked;
});
You will have:
Object {checkbox0: true, checkbox1: false, checkbox2: false, checkbox3: false}
First a
pointed to the string "Dog". Then you changed the variable a
to point at a new string "Dog eats treats". You didn't actually mutate the string "Dog". Strings are immutable, variables can point at whatever they want.
You could use
options(warn=-1)
But note that turning off warning messages globally might not be a good idea.
To turn warnings back on, use
options(warn=0)
(or whatever your default is for warn
, see this answer)
The simpler and current approach for adding header to a single request is:
// Step 1
const yourHeader: HttpHeaders = new HttpHeaders({
Authorization: 'Bearer JWT-token'
});
// POST request
this.http.post(url, body, { headers: yourHeader });
// GET request
this.http.get(url, { headers: yourHeader });
You don't need to iterate through the DataGrid
rows, you can achieve your goal with a more simple solution.
In order to match your row you can iterate through you collection that was bound to your DataGrid.ItemsSource
property then assign this item to you DataGrid.SelectedItem
property programmatically, alternatively you can add it to your DataGrid.SelectedItems
collection if you want to allow the user to select more than one row. See the code below:
<Window x:Class="ProgGridSelection.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="OnWindowLoaded">
<StackPanel>
<DataGrid Name="empDataGrid" ItemsSource="{Binding}" Height="200"/>
<TextBox Name="empNameTextBox"/>
<Button Content="Click" Click="OnSelectionButtonClick" />
</StackPanel>
public partial class MainWindow : Window
{
public class Employee
{
public string Code { get; set; }
public string Name { get; set; }
}
private ObservableCollection<Employee> _empCollection;
public MainWindow()
{
InitializeComponent();
}
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
// Generate test data
_empCollection =
new ObservableCollection<Employee>
{
new Employee {Code = "E001", Name = "Mohammed A. Fadil"},
new Employee {Code = "E013", Name = "Ahmed Yousif"},
new Employee {Code = "E431", Name = "Jasmin Kamal"},
};
/* Set the Window.DataContext, alternatively you can set your
* DataGrid DataContext property to the employees collection.
* on the other hand, you you have to bind your DataGrid
* DataContext property to the DataContext (see the XAML code)
*/
DataContext = _empCollection;
}
private void OnSelectionButtonClick(object sender, RoutedEventArgs e)
{
/* select the employee that his name matches the
* name on the TextBox
*/
var emp = (from i in _empCollection
where i.Name == empNameTextBox.Text.Trim()
select i).FirstOrDefault();
/* Now, to set the selected item on the DataGrid you just need
* assign the matched employee to your DataGrid SeletedItem
* property, alternatively you can add it to your DataGrid
* SelectedItems collection if you want to allow the user
* to select more than one row, e.g.:
* empDataGrid.SelectedItems.Add(emp);
*/
if (emp != null)
empDataGrid.SelectedItem = emp;
}
}
I ve had this problem and it has started after importing our solution to TFS as a new project.I came across this topic and found a quick solution with some inspiration from your answers.
All i needed to do is to rebuild the project thats supposedly lost its metadata file and voila , problem solved.
It's not smart enough to realize it's still a "vector" in math terms.
Say rather that it's smart enough to recognize a difference in dimensionality. :-)
I think the simplest thing you can do is select that row positionally using iloc
, which gives you a Series with the columns as the new index and the values as the values:
>>> df = pd.DataFrame([list(range(5))], columns=["a{}".format(i) for i in range(5)])
>>> df
a0 a1 a2 a3 a4
0 0 1 2 3 4
>>> df.iloc[0]
a0 0
a1 1
a2 2
a3 3
a4 4
Name: 0, dtype: int64
>>> type(_)
<class 'pandas.core.series.Series'>
I had the problem, I had to replace "Not Available" with NA
and my solution goes like this
data <- sapply(data,function(x) {x <- gsub("Not Available",NA,x)})
I switched to a different USB port and it suddenly got recognized...
The guarantees the standard gives you go like this:
1 == sizeof(char) <= sizeof(short) <= sizeof (int) <= sizeof(long) <= sizeof(long long)
So it's perfectly valid for sizeof (int)
and sizeof (long)
to be equal, and many platforms choose to go with this approach. You will find some platforms where int
is 32 bits, long
is 64 bits, and long long
is 128 bits, but it seems very common for sizeof (long)
to be 4.
(Note that long long
is recognized in C from C99 onwards, but was normally implemented as an extension in C++ prior to C++11.)
#sorting first by age then profession,you can change it in function "fun".
a = []
def fun(v):
return (v[1],v[2])
# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John", 8, "Student"])
a.append(["Paul", 8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])
a.sort(key=fun)
print a
class Pin(models.Model):
"""Pin Class"""
image_link = models.CharField(max_length=255, null=True, blank=True)
image = models.ImageField(upload_to='images/', blank=True)
title = models.CharField(max_length=255, null=True, blank=True)
source_name = models.CharField(max_length=255, null=True, blank=True)
source_link = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
tags = models.ForeignKey(Tag, blank=True, null=True)
def __unicode__(self):
"""Unicode class."""
return unicode(self.image_link)
def save(self, *args, **kwargs):
"""Store image locally if we have a URL"""
if self.image_link and not self.image:
result = urllib.urlretrieve(self.image_link)
self.image.save(os.path.basename(self.image_link), File(open(result[0], 'r')))
self.save()
super(Pin, self).save()
The below code gets the full path, where the anchor points:
document.getElementById("aaa").href; // http://example.com/sec/IF00.html
while the one below gets the value of the href
attribute:
document.getElementById("aaa").getAttribute("href"); // sec/IF00.html
The methods provide different layers of abstraction.
$.ajax()
gives you full control over the Ajax request. You should use it if the other methods don't fullfil your needs.
$.get()
executes an Ajax GET
request. The returned data (which can be any data) will be passed to your callback handler.
$(selector).load()
will execute an Ajax GET
request and will set the content of the selected returned data (which should be either text or HTML).
It depends on the situation which method you should use. If you want to do simple stuff, there is no need to bother with $.ajax()
.
E.g. you won't use $.load()
, if the returned data will be JSON which needs to be processed further. Here you would either use $.ajax()
or $.get()
.
This is only applicable using gnome zenity. Zenity provides a great native interface to bash scripts: https://help.gnome.org/users/zenity/stable/
From Zenity Progress Bar Example:
#!/bin/sh
(
echo "10" ; sleep 1
echo "# Updating mail logs" ; sleep 1
echo "20" ; sleep 1
echo "# Resetting cron jobs" ; sleep 1
echo "50" ; sleep 1
echo "This line will just be ignored" ; sleep 1
echo "75" ; sleep 1
echo "# Rebooting system" ; sleep 1
echo "100" ; sleep 1
) |
zenity --progress \
--title="Update System Logs" \
--text="Scanning mail logs..." \
--percentage=0
if [ "$?" = -1 ] ; then
zenity --error \
--text="Update canceled."
fi
You can do either:
$("h1").css("background-color", "yellow");
Or:
$("h1").css({backgroundColor: "yellow"});
Seems like Firebug or whatever Debugger you are using, is not initialized properly. Are you sure Firebug is fully initialized when you try to access the console.log()-method? Check the Console-Tab (if it's set to activated).
Another possibility could be, that you overwrite the console-Object yourself anywhere in the code.
This thread is pretty old I suppose, but in case anyone else stumbles across this question... I had to grab a value from the selected row of a table, but I didn't want to show the column that row was from. I used hideCol, but had the same problem as Andy where it looked messy. To fix it (call it a hack) I just re-set the width of the grid.
jQuery(document).ready(function() {
jQuery("#ItemGrid").jqGrid({
...,
width: 700,
...
}).hideCol('StoreId').setGridWidth(700)
Since my row widths are automatic, when I reset the width of the table it reset the column widths but excluded the hidden one, so they filled in the gap.
class is used when u want to set properties for a group of elements, but id can be set for only one element.
According to this: http://www.vistax64.com/vista-installation-setup/33219-regsvr32-error-0x80004005.html
Run it in a elevated command prompt.
I had similar symptoms recently. Turned out it was caused by the Subversion server being unavailable - once that was restarted I was able to right-click. My environment was Eclipse Luna with Subclipse.
So worth checking that any connected source control systems are operational. Hope that helps.
We can use this:
DELETE FROM table_name WHERE date_column <
CAST(CONVERT(char(8), (DATEADD(day,-30,GETDATE())), 112) AS datetime)
But a better option is to use:
DELETE FROM table_name WHERE DATEDIFF(dd, date_column, GETDATE()) > 30
The former is not sargable (i.e. functions on the right side of the expression so it can’t use index) and takes 30 seconds, the latter is sargable and takes less than a second.
is it still actual?
As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>
, then you wrote <target name="build-subprojects"/>
(it does nothing). Could it be a reason?
Does this <echo message="${ant.project.name}: ${ant.file}"/>
print appropriate message? If no then target is not running.
Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277
I was having the same issue and this works excellently.
Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting
'Display complete contents in tooltip even though column display cuts off part of it.
DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
SQL is Structured Query Language
MySQL is a relational database management system. You can submit SQL queries to the MySQL database to store, retrieve, modify or delete data.
Try this......
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
// Background view is at index 0, content view at index 1
if let bgView = view.subviews[0] as? UIView
{
// do your stuff
}
view.layer.borderColor = UIColor.magentaColor().CGColor
view.layer.borderWidth = 1
}
Just wanted to mention, that you also may have to set the https_proxy
OS environment variable in case https URLs need to be accessed.
In my case it was not obvious to me and I tried for hours to discover this.
My use case: Win 7, jython-standalone-2.5.3.jar, setuptools installation via ez_setup.py
I have done with easy way:
Please check screen shot for the same.
CustomProgressBarActivity.java:
public class CustomProgressBarActivity extends AppCompatActivity {
private TextView txtProgress;
private ProgressBar progressBar;
private int pStatus = 0;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_progressbar);
txtProgress = (TextView) findViewById(R.id.txtProgress);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
new Thread(new Runnable() {
@Override
public void run() {
while (pStatus <= 100) {
handler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(pStatus);
txtProgress.setText(pStatus + " %");
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
pStatus++;
}
}
}).start();
}
}
activity_custom_progressbar.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.skholingua.android.custom_progressbar_circular.MainActivity" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:indeterminate="false"
android:max="100"
android:progress="0"
android:progressDrawable="@drawable/custom_progressbar_drawable"
android:secondaryProgress="0" />
<TextView
android:id="@+id/txtProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/progressBar"
android:layout_centerInParent="true"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</RelativeLayout>
custom_progressbar_drawable.xml:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="-90"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="270" >
<shape
android:shape="ring"
android:useLevel="false" >
<gradient
android:centerY="0.5"
android:endColor="#FA5858"
android:startColor="#0099CC"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Hope this will help you.
For interactive work, Matplotlib is the mature standard. It provides an OO-style API as well as a Matlab-style interactive API.
Chaco is a more modern plotting library from the folks at Enthought. It uses Enthought's Kiva vector drawing library and currently works only with Wx and Qt with OpenGL on the way (Matplotlib has backends for Tk, Qt, Wx, Cocoa, and many image types such as PDF, EPS, PNG, etc.). The main advantages of Chaco are its speed relative to Matplotlib and its integration with Enthought's Traits API for interactive applications.
i work with this npm package unix-system-timezone
It is worth mentioning that one can check the characters in the string against Unicode categories - numbers, uppercase, lowercase, currencies and more. Here are two examples checking for numbers in a string using Linq:
var containsNumbers = s.Any(Char.IsNumber);
var isNumber = s.All(Char.IsNumber);
For clarity, the syntax above is a shorter version of:
var containsNumbers = s.Any(c=>Char.IsNumber(c));
var isNumber = s.All(c=>Char.IsNumber(c));
Link to unicode categories on MSDN:
I know this question is about Linux, but in case someone stumbles on this problem on Mac like I did here is the solution for that. I had the exact same problem on Mac because ffmpeg
is not installed by default apparently, and so I could solve it using:
brew install yasm
brew install ffmpeg
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
try
total.Text = DateTime.Now.ToString()
or
Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()
You declare Start
as an Integer
, while you are trying to put a DateTime
in it, which is not possible.
If you still want to group only by one column (as I wanted) you can nest the query:
select c1, count(*) from (select distinct c1, c2 from t) group by c1
You could throw the enum value and string into an STL map. Then you could use it like so.
return myStringMap[Enum::Apple];
You have an error in you script tag construction, this:
<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
Should look like this:
<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.
UPDATE
But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
I made a dynamic proc which turns any random query into an HTML table, so you don't have to hardcode columns like in the other responses.
-- Description: Turns a query into a formatted HTML table. Useful for emails.
-- Any ORDER BY clause needs to be passed in the separate ORDER BY parameter.
-- =============================================
CREATE PROC [dbo].[spQueryToHtmlTable]
(
@query nvarchar(MAX), --A query to turn into HTML format. It should not include an ORDER BY clause.
@orderBy nvarchar(MAX) = NULL, --An optional ORDER BY clause. It should contain the words 'ORDER BY'.
@html nvarchar(MAX) = NULL OUTPUT --The HTML output of the procedure.
)
AS
BEGIN
SET NOCOUNT ON;
IF @orderBy IS NULL BEGIN
SET @orderBy = ''
END
SET @orderBy = REPLACE(@orderBy, '''', '''''');
DECLARE @realQuery nvarchar(MAX) = '
DECLARE @headerRow nvarchar(MAX);
DECLARE @cols nvarchar(MAX);
SELECT * INTO #dynSql FROM (' + @query + ') sub;
SELECT @cols = COALESCE(@cols + '', '''''''', '', '''') + ''['' + name + ''] AS ''''td''''''
FROM tempdb.sys.columns
WHERE object_id = object_id(''tempdb..#dynSql'')
ORDER BY column_id;
SET @cols = ''SET @html = CAST(( SELECT '' + @cols + '' FROM #dynSql ' + @orderBy + ' FOR XML PATH(''''tr''''), ELEMENTS XSINIL) AS nvarchar(max))''
EXEC sys.sp_executesql @cols, N''@html nvarchar(MAX) OUTPUT'', @html=@html OUTPUT
SELECT @headerRow = COALESCE(@headerRow + '''', '''') + ''<th>'' + name + ''</th>''
FROM tempdb.sys.columns
WHERE object_id = object_id(''tempdb..#dynSql'')
ORDER BY column_id;
SET @headerRow = ''<tr>'' + @headerRow + ''</tr>'';
SET @html = ''<table border="1">'' + @headerRow + @html + ''</table>'';
';
EXEC sys.sp_executesql @realQuery, N'@html nvarchar(MAX) OUTPUT', @html=@html OUTPUT
END
GO
Usage:
DECLARE @html nvarchar(MAX);
EXEC spQueryToHtmlTable @html = @html OUTPUT, @query = N'SELECT * FROM dbo.People', @orderBy = N'ORDER BY FirstName';
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Foo',
@recipients = '[email protected];',
@subject = 'HTML email',
@body = @html,
@body_format = 'HTML',
@query_no_truncate = 1,
@attach_query_result_as_file = 0;
Related: Here is similar code to turn any arbitrary query into a CSV string.
Just just using Transformers It did not work for me I was getting type cast exception.
sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class))
did notwork because I was getting Array of Object in the return list element not the fixed MYEngityName type of list element.
It worked for me when I make following changes When I have added sqlQuery.addScalar(-)
each selected column and its type and for specific String type column we dont have to map its type. like addScalar("langCode");
And I have join MYEngityName with NextEnity we cant just select *
in the Query it will give array of Object in the return list.
Below code sample :
session = ht.getSessionFactory().openSession();
String sql = new StringBuffer("Select txnId,nft.mId,count,retryReason,langCode FROM MYEngityName nft INNER JOIN NextEntity m on nft.mId = m.id where nft.txnId < ").append(lastTxnId)
.append(StringUtils.isNotBlank(regionalCountryOfService)? " And m.countryOfService in ( "+ regionalCountryOfService +" )" :"")
.append(" order by nft.txnId desc").toString();
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class));
sqlQuery.addScalar("txnId",Hibernate.LONG)
.addScalar("merchantId",Hibernate.INTEGER)
.addScalar("count",Hibernate.BYTE)
.addScalar("retryReason")
.addScalar("langCode");
sqlQuery.setMaxResults(maxLimit);
return sqlQuery.list();
It might help some one. in this way work for me.
We have the following string which is a valid JSON ...
Clearly the JSON parser disagrees!
However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.
You need to find what JSON is actually being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for JsonParseException
... then find out what is in the ByteArrayInputStream
that it is attempting to parse.
To elaborate on @serine's answer and illustrate working with non-trivial multi-valued condition: I had a need to show a "dim-out" overlay on an item for the boolean condition NOT a AND (b OR NOT c)
.
For background, this is a "Multiple Choice" question. If the user picks a wrong answer it becomes disabled (dimmed out and cannot be selected again). An automated agent has the ability to focus on any particular choice to give an explanation (border highlighted). When the agent focuses on an item, it should not be dimmed out even if it is disabled. All items that are not in focused are marked de-focused, and should be dimmed out.
The logic for dimming is thus:
NOT IsFocused AND (IsDefocused OR NOT Enabled)
To implement this logic, I made a generic IMultiValueConverter
named (awkwardly) to match my logic
// 'P' represents a parenthesis
// ! a && ( b || ! c )
class NOT_a_AND_P_b_OR_NOT_c_P : IMultiValueConverter
{
// redacted [...] for brevity
public object Convert(object[] values, ...)
{
bool a = System.Convert.ToBoolean(values[0]);
bool b = System.Convert.ToBoolean(values[1]);
bool c = System.Convert.ToBoolean(values[2]);
return !a && (b || !c);
}
...
}
In the XAML I use this in a MultiDataTrigger
in a <Style><Style.Triggers>
resource
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<!-- when the equation is TRUE ... -->
<Condition Value="True">
<Condition.Binding>
<MultiBinding Converter="{StaticResource NOT_a_AND_P_b_OR_NOT_c_P}">
<!-- NOT IsFocus AND ( IsDefocused OR NOT Enabled ) -->
<Binding Path="IsFocus"/>
<Binding Path="IsDefocused" />
<Binding Path="Enabled" />
</MultiBinding>
</Condition.Binding>
</Condition>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<!-- ... show the 'dim-out' overlay -->
<Setter Property="Visibility" Value="Visible" />
</MultiDataTrigger.Setters>
</MultiDataTrigger>
And for completeness sake, my converter is defined in a ResourceDictionary
<ResourceDictionary xmlns:conv="clr-namespace:My.Converters" ...>
<conv:NOT_a_AND_P_b_OR_NOT_c_P x:Key="NOT_a_AND_P_b_OR_NOT_c_P" />
</ResourceDictionary>
With LINQ, you can transform the array of uninitialized elements into the new collection of created objects with one line of code.
var houses = new GameObject[200].Select(h => new GameObject()).ToArray();
Actually, you can use any other source for this, even generated sequence of integers:
var houses = Enumerable.Repeat(0, 200).Select(h => new GameObject()).ToArray();
However, the first case seems to me more readable, although the type of original sequence is not important.
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
c:\opencv\samples\cpp
.If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:
SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL
The top answer here didn't quite fix the problem, although it's probably a necessary step:
sudo chown -R user:user ~/.local/share/jupyter
(user should be whoever is the logged in user running the notebook server) This changes the folder owner to the user running the server, giving it full access.
After doing this, the error message said it didn't have permission to create the checkpoint file in ~/.ipynb_checkpoints/ so I also changed ownership of that folder (which was previously root)
sudo chown -R user:user ~/.ipynb_checkpoints/
And then I was able to create and save a notebook!
file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo
Alternatively, if you're stuck with fopen()
you can use the w
or w+
modes:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
Default values cannot be supplied for parameters that are not declared 'optional
'
Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)
In your WebApiConfig
config.Routes.MapHttpRoute( _
name:="books", _
routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
)
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
You can just use return
to end the method's execution
CODE:
import codecs
path="D:\\Users\\html\\abc.html"
file=codecs.open(path,"rb")
file1=file.read()
file1=str(file1)
Another possible reason
resConfigs "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"
can be source of this issue
Now (2020) NetBeans 11 does it automatically with the "Build" command (right click on the project's name and choose "Build")
I have tried similar issue and works fine, try it. It can handle different orientations between PDFs.
// array to hold list of PDF files to be merged
$files = array("a.pdf", "b.pdf", "c.pdf");
$pageCount = 0;
// initiate FPDI
$pdf = new FPDI();
// iterate through the files
foreach ($files AS $file) {
// get the page count
$pageCount = $pdf->setSourceFile($file);
// iterate through all pages
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// import a page
$templateId = $pdf->importPage($pageNo);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
// create a page (landscape or portrait depending on the imported page size)
if ($size['w'] > $size['h']) {
$pdf->AddPage('L', array($size['w'], $size['h']));
} else {
$pdf->AddPage('P', array($size['w'], $size['h']));
}
// use the imported page
$pdf->useTemplate($templateId);
$pdf->SetFont('Helvetica');
$pdf->SetXY(5, 5);
$pdf->Write(8, 'Generated by FPDI');
}
}
You probably already know about $(document).ready(...). What you need is a preloading mechanism; something that fetches data (text or images or whatever) before showing it off. This can make a site feel much more professional.
Take a look at jQuery.Preload (there are others). jQuery.Preload has several ways of triggering preloading, and also provides callback functionality (when the image is preloaded, then show it). I have used it heavily, and it works great.
Here's how easy it is to get started with jQuery.Preload:
$(function() {
// First get the preload fetches under way
$.preload(["images/button-background.png", "images/button-highlight.png"]);
// Then do anything else that you would normally do here
doSomeStuff();
});
Here are some extension methods for getting that information (it also includes the ID):
public static class HtmlRequestHelper
{
public static string Id(this HtmlHelper htmlHelper)
{
var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;
if (routeValues.ContainsKey("id"))
return (string)routeValues["id"];
else if (HttpContext.Current.Request.QueryString.AllKeys.Contains("id"))
return HttpContext.Current.Request.QueryString["id"];
return string.Empty;
}
public static string Controller(this HtmlHelper htmlHelper)
{
var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;
if (routeValues.ContainsKey("controller"))
return (string)routeValues["controller"];
return string.Empty;
}
public static string Action(this HtmlHelper htmlHelper)
{
var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;
if (routeValues.ContainsKey("action"))
return (string)routeValues["action"];
return string.Empty;
}
}
Usage:
@Html.Controller();
@Html.Action();
@Html.Id();
Try this
new_df = pd.merge(A_df, B_df, how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html
left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns
right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs
Personally I never round anything. Keep it as resolute as possible, since rounding is a bit of a red herring in CS anyway. But you do want to format data for your users, and to that end, I find that string.Format("{0:0.00}", number)
is a good approach.
Nice question/answers.
Just want to point out that C pointers and arrays are not the same, although in this case the difference is not essential.
Consider the following declarations:
int a[10];
int* p = a;
In a.out
, the symbol a
is at an address that's the beginning of the array, and symbol p
is at an address where a pointer is stored, and the value of the pointer at that memory location is the beginning of the array.
If you import the module (.py) file you are creating now from another python script it will not execute the code within
if __name__ == '__main__':
...
If you run the script directly from the console, it will be executed.
Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.
This is expanded upon a little more at python.berkely.edu
You are binding the click
event to anchors with an href attribute with value sign_new
.
Either bind anchors with class sign_new
or bind anchors with href value #sign_up
. I would prefer the former.
import java.util.*;
class GetCurrentmonth
{
public static void main(String args[])
{
int month;
GregorianCalendar date = new GregorianCalendar();
month = date.get(Calendar.MONTH);
month = month+1;
System.out.println("Current month is " + month);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
[RoutePrefix("File")]
[Route("{action=index}")]
public class FileController : Controller
{
// GET: File
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
[Route("Image/{extension?}/{filename}")]
public ActionResult Image(string extension, string filename)
{
var dir = Server.MapPath("/app_data/images");
var path = Path.Combine(dir, filename+"."+ (extension!=null? extension:"jpg"));
// var extension = filename.Substring(0,filename.LastIndexOf("."));
return base.File(path, "image/jpeg");
}
}
}
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
I'll assume that if you're restoring a db, you don't care about any existing transactions on that db. Right? If so, this should work for you:
USE master
GO
ALTER DATABASE AdventureWorksDW
SET SINGLE_USER
--This rolls back all uncommitted transactions in the db.
WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE AdventureWorksDW
FROM ...
...
GO
Now, one additional item to be aware. After you set the db into single user mode, someone else may attempt to connect to the db. If they succeed, you won't be able to proceed with your restore. It's a race! My suggestion is to run all three statements at once.
No answer like this:
SELECT * FROM table WHERE something LIKE ('bla% %foo% batz%')
In oracle no problem.
Converting my comment into an answer to complement @Kiran Chala's answer as it seems helpful for the audiences-
When we mark a parameter as optional in the action uri using ?
character then we must provide default values to the parameters in the method signature as shown below:
MyMethod(string name = "someDefaultValue", int? Id = null)
This error is probably related to a byte order mark (BOM) prior to the actual XML content. You need to parse the returned String and discard the BOM, so SAXParser can process the document correctly.
You will find a possible solution here.
Think of it as your stylesheet(s) referring to ("selecting") elements in your HTML page, not the other way around.
Easiest way to do it with javax.xml.bind.DatatypeConverter
:
String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
byte[] s = DatatypeConverter.parseHexBinary(hex);
System.out.println(new String(s));
You can't do a bulk-update in SSIS within a dataflow task with the OOB components.
The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.
Stage data
Set based updates
You'll get much better performance with a pattern like this versus using the OLE DB Command
transformation for anything but trivial amounts of data.
If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.
Assuming id
is the primary key of table :
SELECT * FROM table WHERE id BETWEEN 10 AND 50
For first 20 results
SELECT * FROM table order by id limit 20;
Start with the use of tabs - the \t character modifier. It will advance to a fixed location (columns, terminal lingo).
However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).
To fix that, write your "OK/NOK" stuff using a fixed number of tabs (5? 6?, try it). Then return (\r) without new-lining, and write your message.
I tried all of these and could not get my break-point working...
What i did to fix this issue was
In the page where my break-point was not hitting, i selected the folder > add an existing item and then select the page from its save path. This allowed the break point to start working.
Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.
Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.
ssh kev@server1 './test/foo.sh'
Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).
select to_char(sysdate, 'Month') from dual
in your example will be:
select to_char(to_date('15-11-2010', 'DD-MM-YYYY'), 'Month') from dual
By using the PushAsync() method you can push and PopModalAsync() you can pop pages to and from the navigation stack. In my code example below I have a Navigation page (Root Page) and from this page I push a content page that is a login page once I am complete with my login page I pop back to the root page
~~~ Navigation can be thought of as a last-in, first-out stack of Page objects.To move from one page to another an application will push a new page onto this stack. To return back to the previous page the application will pop the current page from the stack. This navigation in Xamarin.Forms is handled by the INavigation interface
Xamarin.Forms has a NavigationPage class that implements this interface and will manage the stack of Pages. The NavigationPage class will also add a navigation bar to the top of the screen that displays a title and will also have a platform appropriate Back button that will return to the previous page. The following code shows how to wrap a NavigationPage around the first page in an application:
Reference to content listed above and a link you should review for more information on Xamarin Forms, see the Navigation section:
http://developer.xamarin.com/guides/cross-platform/xamarin-forms/introduction-to-xamarin-forms/
~~~
public class MainActivity : AndroidActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Xamarin.Forms.Forms.Init(this, bundle);
// Set our view from the "main" layout resource
SetPage(BuildView());
}
static Page BuildView()
{
var mainNav = new NavigationPage(new RootPage());
return mainNav;
}
}
public class RootPage : ContentPage
{
async void ShowLoginDialog()
{
var page = new LoginPage();
await Navigation.PushModalAsync(page);
}
}
//Removed code for simplicity only the pop is displayed
private async void AuthenticationResult(bool isValid)
{
await navigation.PopModalAsync();
}
For Java < 7 you can use if-else along with Exception:
try {
// common logic to handle both exceptions
} catch (Exception ex) {
if (ex instanceof Exception1 || ex instanceof Exception2) {
}
else {
throw ex;
// or if you don't want to have to declare Exception use
// throw new RuntimeException(ex);
}
}
Edited and replaced Throwable with Exception.
If you have some panels or groupboxes reset fields should be recursive.
public class Utilities
{
public static void ResetAllControls(Control form)
{
foreach (Control control in form.Controls)
{
RecursiveResetForm(control);
}
}
private void RecursiveResetForm(Control control)
{
if (control.HasChildren)
{
foreach (Control subControl in control.Controls)
{
RecursiveResetForm(subControl);
}
}
switch (control.GetType().Name)
{
case "TextBox":
TextBox textBox = (TextBox)control;
textBox.Text = null;
break;
case "ComboBox":
ComboBox comboBox = (ComboBox)control;
if (comboBox.Items.Count > 0)
comboBox.SelectedIndex = 0;
break;
case "CheckBox":
CheckBox checkBox = (CheckBox)control;
checkBox.Checked = false;
break;
case "ListBox":
ListBox listBox = (ListBox)control;
listBox.ClearSelected();
break;
case "NumericUpDown":
NumericUpDown numericUpDown = (NumericUpDown)control;
numericUpDown.Value = 0;
break;
}
}
}
Some other more primitive options that avoid classes/reference types:
Array method
private struct PublishStatusses
{
public static string[] Desc = {
"Not Completed",
"Completed",
"Error"
};
public enum Id
{
NotCompleted = 0,
Completed,
Error
};
}
Usage
string desc = PublishStatusses.Desc[(int)PublishStatusses.Id.Completed];
Nested struct method
private struct PublishStatusses
{
public struct NotCompleted
{
public const int Id = 0;
public const string Desc = "Not Completed";
}
public struct Completed
{
public const int Id = 1;
public const string Desc = "Completed";
}
public struct Error
{
public const int Id = 2;
public const string Desc = "Error";
}
}
Usage
int id = PublishStatusses.NotCompleted.Id;
string desc = PublishStatusses.NotCompleted.Desc;
Update (03/09/2018)
A hybrid of Extension Methods and the first technique above.
I prefer enums to be defined where they "belong" (closest to their source of origin and not in some common, global namespace).
namespace ViewModels
{
public class RecordVM
{
//public enum Enum { Minutes, Hours }
public struct Enum
{
public enum Id { Minutes, Hours }
public static string[] Name = { "Minute(s)", "Hour(s)" };
}
}
}
The extension method seems suited for a common area, and the "localized" definition of the enum now makes the extension method more verbose.
namespace Common
{
public static class EnumExtensions
{
public static string Name(this RecordVM.Enum.Id id)
{
return RecordVM.Enum.Name[(int)id];
}
}
}
A usage example of the enum and it's extension method.
namespace Views
{
public class RecordView
{
private RecordDataFieldList<string, string> _fieldUnit;
public RecordView()
{
_fieldUnit.List = new IdValueList<string, string>
{
new ListItem<string>((int)RecordVM.Enum.Id.Minutes, RecordVM.Enum.Id.Minutes.Name()),
new ListItem<string>((int)RecordVM.Enum.Id.Hours, RecordVM.Enum.Id.Hours.Name())
};
}
private void Update()
{
RecordVM.Enum.Id eId = DetermineUnit();
_fieldUnit.Input.Text = _fieldUnit.List.SetSelected((int)eId).Value;
}
}
}
Note: I actually decided to eliminate the Enum
wrapper (and Name
array), since it's best that the name strings come from a resource (ie config file or DB) instead of being hard-coded, and because I ended up putting the extension method in the ViewModels
namespace (just in a different, "CommonVM.cs" file). Plus the whole .Id
thing becomes distracting and cumbersome.
namespace ViewModels
{
public class RecordVM
{
public enum Enum { Minutes, Hours }
//public struct Enum
//{
// public enum Id { Minutes, Hours }
// public static string[] Name = { "Minute(s)", "Hour(s)" };
//}
}
}
CommonVM.cs
//namespace Common
namespace ViewModels
{
public static class EnumExtensions
{
public static string Name(this RecordVM.Enum id)
{
//return RecordVM.Enum.Name[(int)id];
switch (id)
{
case RecordVM.Enum.Minutes: return "Minute(s)";
case RecordVM.Enum.Hours: return "Hour(s)";
default: return null;
}
}
}
}
A usage example of the enum and it's extension method.
namespace Views
{
public class RecordView
{
private RecordDataFieldList<string, string> _fieldUnit
public RecordView()
{
_fieldUnit.List = new IdValueList<string, string>
{
new ListItem<string>((int)RecordVM.Enum.Id.Minutes, RecordVM.Enum.Id.Minutes.Name()),
new ListItem<string>((int)RecordVM.Enum.Id.Hours, RecordVM.Enum.Id.Hours.Name())
};
}
private void Update()
{
RecordVM.Enum eId = DetermineUnit();
_fieldUnit.Input.Text = _fieldUnit.List.SetSelected((int)eId).Value;
}
}
}
def str2bool(str):
if isinstance(str, basestring) and str.lower() in ['0','false','no']:
return False
else:
return bool(str)
idea: check if you want the string to be evaluated to False; otherwise bool() returns True for any non-empty string.
As of WPF 4.5 you can bind directly to static properties and have the binding automatically update when your property is changed. You do need to manually wire up a change event to trigger the binding updates.
public class VersionManager
{
private static String _filterString;
/// <summary>
/// A static property which you'd like to bind to
/// </summary>
public static String FilterString
{
get
{
return _filterString;
}
set
{
_filterString = value;
// Raise a change event
OnFilterStringChanged(EventArgs.Empty);
}
}
// Declare a static event representing changes to your static property
public static event EventHandler FilterStringChanged;
// Raise the change event through this static method
protected static void OnFilterStringChanged(EventArgs e)
{
EventHandler handler = FilterStringChanged;
if (handler != null)
{
handler(null, e);
}
}
static VersionManager()
{
// Set up an empty event handler
FilterStringChanged += (sender, e) => { return; };
}
}
You can now bind your static property just like any other:
<TextBox Text="{Binding Path=(local:VersionManager.FilterString)}"/>
Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.
If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with
foo.to_s == bar.to_s
It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string
foo == bar.to_s
But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.
Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.
Ruby 2.2 introduced garbage collection of symbols.
To install any other package I have to use the latest version of pip, since the 9.0.1
has this SSL problem. To upgrade the pip by pip itself, I have to solve this SSL problem first.
To jump out of this endless loop, I find this only way that works for me.
.whl
file of the latest version.sudo pip install pip-10.0.1-py2.py3-none-any.whl
Now the pip is the latest version and can install anything.
Normally, when the user tabs from field to field in a form (in a browser that allows tabbing, not all browsers do) the order is the order the fields appear in the HTML code.
However, sometimes you want the tab order to flow a little differently. In that case, you can number the fields using TABINDEX. The tabs then flow in order from lowest TABINDEX to highest.
More info on this can be found here w3
another good illustration can be found here
To fix the problem, I tried to run
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
However It didn't work for me. I have to run another command line in CMD window as administrator. Here is the command:
dism /online /enable-feature /featurename:IIS-ASPNET45
or
dism /online /enable-feature /featurename:IIS-ASPNET45 /all
Hope it will help.
The Left join in this query is pointless:
UPDATE md SET md.status = '3'
FROM pd_mounting_details AS md
LEFT OUTER JOIN pd_order_ecolid AS oe ON md.order_data = oe.id
It would update all rows of pd_mounting_details
, whether or not a matching row exists in pd_order_ecolid
. If you wanted to only update matching rows, it should be an inner join.
If you want to apply some condition based on the join occurring or not, you need to add a WHERE
clause and/or a CASE
expression in your SET
clause.
x = float(raw_input("enter number between 0 and 1: "))
p = 0
while ((2**p)*x) %1 != 0:
p += 1
# print p
num = int (x * (2 ** p))
# print num
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num / 2
for i in range (p - len(result)):
result = '0' + result
result = result[0:-p] + '.' + result[-p:]
print result #this will print result for the decimal portion
You comment:
valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....
If you are interested in each term, then write the code so it deals with each. For example.
for b in valeur<=0.6:
if b:
print ("this works")
else:
print ("valeur is too high")
This will write 2 lines.
The error is produced by numpy
code when you try to use it a context that expects a single, scalar, value. if b:...
can only do one thing. It does not, by itself, iterate through the elements of b
doing a different thing for each.
You could also cast that iteration as list comprehension, e.g.
['yes' if b else 'no' for b in np.array([True, False, True])]
Calling conventions defines how parameters are passed in the registers when calling or being called by other program. And the best source of these convention is in the form of ABI standards defined for each these hardware. For ease of compilation, the same ABI is also used by userspace and kernel program. Linux/Freebsd follow the same ABI for x86-64 and another set for 32-bit. But x86-64 ABI for Windows is different from Linux/FreeBSD. And generally ABI does not differentiate system call vs normal "functions calls". Ie, here is a particular example of x86_64 calling conventions and it is the same for both Linux userspace and kernel: http://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/ (note the sequence a,b,c,d,e,f of parameters):
Performance is one of the reasons for these ABI (eg, passing parameters via registers instead of saving into memory stacks)
For ARM there is various ABI:
http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.subset.swdev.abi/index.html
ARM64 convention:
http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
For Linux on PowerPC:
http://refspecs.freestandards.org/elf/elfspec_ppc.pdf
http://www.0x04.net/doc/elf/psABI-ppc64.pdf
And for embedded there is the PPC EABI:
http://www.freescale.com/files/32bit/doc/app_note/PPCEABI.pdf
This document is good overview of all the different conventions:
If you are having this problem and are using Qt - you need to link qtmain.lib or qtmaind.lib
You can Use Sql Server Integration Service Packages specifically designed for Import and Export operation.
VS has a package for developing these packages if your fully install Sql Server.
Integration Services in Business Intelligence Development Studio
On pure JS:
let select = document.getElementById("select_id")
let to_hide = select[select.selectedIndex];
to_hide.setAttribute('hidden', 'hidden');
to unhide just
to_hide.removeAttr('hidden');
or
to_hide.hidden = true; // to hide
to_hide.hidden = false; // to unhide
Here's a workaround for installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable on a system with a 32-bit MS Office version installed:
Now you can start a 32-bit MS Office application without the "re-configuring" issue. Note that the "mso.dll" registry value will already be present if a 64-bit version of MS Office is installed. In this case the value should not be deleted or renamed.
Also if you do not want to use the "/passive" command line parameter you can edit the AceRedist.msi file to remove the MS Office architecture check:
You can now use this file to install the Microsoft Access Database Engine 2010 redistributable on a system where a "conflicting" version of MS Office is installed (e.g. 64-bit version on system with 32-bit MS Office version) Make sure that you rename the "mso.dll" registry value as explained above (if needed).
use this to clear the previous keyboard buffer before scanning the string it will solve your problem scanner.nextLine();//this is to clear the keyboard buffer
For Kotlin, if you want to be sure that the format is "Aaaaaaaaa" you can use :
myString.toLowerCase(Locale.getDefault()).capitalize()
Another way to do this, if you have already initialised a form (with or without data), and you need to add further data before displaying it:
form = Form(request.POST.form)
form.data['Email'] = GetEmailString()
In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.
Instead, declare valueToPush
as an object and push that onto cookie_value_add
:
// Create valueToPush as an object {} rather than an array []
var valueToPush = {};
// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
// View the structure of cookie_value_add
console.dir(cookie_value_add);
Simple URL :
https://www.google.com/maps/dir/?api=1&destination=lat,lng
This url is specific for routing.
Reference : https://developers.google.com/maps/documentation/urls/guide#directions-action
The original code you suggest is the best way.
Matlab is extremely good at vectorized operations such as this, at least for large vectors.
The built-in norm function is very fast. Here are some timing results:
V = rand(10000000,1);
% Run once
tic; V1=V/norm(V); toc % result: 0.228273s
tic; V2=V/sqrt(sum(V.*V)); toc % result: 0.325161s
tic; V1=V/norm(V); toc % result: 0.218892s
V1 is calculated a second time here just to make sure there are no important cache penalties on the first call.
Timing information here was produced with R2008a x64 on Windows.
EDIT:
Revised answer based on gnovice's suggestions (see comments). Matrix math (barely) wins:
clc; clear all;
V = rand(1024*1024*32,1);
N = 10;
tic; for i=1:N, V1 = V/norm(V); end; toc % 6.3 s
tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 9.3 s
tic; for i=1:N, V3 = V/sqrt(V'*V); end; toc % 6.2 s ***
tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 9.2 s
tic; for i=1:N, V1=V/norm(V); end; toc % 6.4 s
IMHO, the difference between "norm(V)" and "sqrt(V'*V)" is small enough that for most programs, it's best to go with the one that's more clear. To me, "norm(V)" is clearer and easier to read, but "sqrt(V'*V)" is still idiomatic in Matlab.
Also look up ArrayAdapter interface:
ArrayAdapter(Context context, int textViewResourceId, List<T> objects)
JQUERY
$("#video1").bind("ended", function() {
//TO DO: Your code goes here...
});
HTML
<video id="video1" width="420">
<source src="path/filename.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
Event types HTML Audio and Video DOM Reference
This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:
window.getSelection().anchorNode.textContent.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset)
You have to wrap your Javascript-Code with $(document).ready(function(){});
Look this JSfiddle.
JS Code:
$(document).ready(function() {
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
});
Based on Ahmed's answer, after some cleaning up and generalization, including the other "Find" parameters, so we can use this function in any situation:
'Uses Range.Find to get a range of all find results within a worksheet
' Same as Find All from search dialog box
'
Function FindAll(rng As Range, What As Variant, Optional LookIn As XlFindLookIn = xlValues, Optional LookAt As XlLookAt = xlWhole, Optional SearchOrder As XlSearchOrder = xlByColumns, Optional SearchDirection As XlSearchDirection = xlNext, Optional MatchCase As Boolean = False, Optional MatchByte As Boolean = False, Optional SearchFormat As Boolean = False) As Range
Dim SearchResult As Range
Dim firstMatch As String
With rng
Set SearchResult = .Find(What, , LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)
If Not SearchResult Is Nothing Then
firstMatch = SearchResult.Address
Do
If FindAll Is Nothing Then
Set FindAll = SearchResult
Else
Set FindAll = Union(FindAll, SearchResult)
End If
Set SearchResult = .FindNext(SearchResult)
Loop While Not SearchResult Is Nothing And SearchResult.Address <> firstMatch
End If
End With
End Function
Sometimes this syntax wont work:
df[['col1','col2']] = df[['col1','col2']].fillna()
Use the following instead:
df['col1','col2']
<style type="text/css" media="print">
@page {
size: auto;
margin: 0;
}
</style>
//now set manual padding to body
<style>
body{
padding-left: 1.3cm;
padding-right: 1.3cm;
padding-top: 1.1cm;
}
</style>
You should provide a selector to the on
function:
$(document).on('change', 'input', function() {
// Does some stuff and logs the event to the console
});
In that case, it will work as you expected. Also, it is better to specify some element instead of document.
Read this article for better understanding: http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/