I think you want to return a REFCURSOR:
create function test_cursor
return sys_refcursor
is
c_result sys_refcursor;
begin
open c_result for
select * from dual;
return c_result;
end;
Update: If you need to call this from SQL, use a table function like @Tony Andrews suggested.
As far as I know this:
div[class=yourclass] table { your style here; }
or in your case even this:
div.yourclass table { your style here; }
(but this will work for elements with yourclass
that might not be div
s) will affect only tables inside yourclass
. And, as Ken says, the > is not supported everywhere (and div[class=yourclass]
too, so use the point notation for classes).
On the Chrome console right click with the mouse and We have the option to clear the console
Make sure you follow these steps in order:
Generate the App ID at https://developer.apple.com/account/ios/identifier/bundle
Generate your app from iTunes Connect selecting the Bundle ID created in step one
Upload the IPA from Application Loader or XCode
This counts the rows of the inner query:
select count(*) from (
select count(SID)
from Test
where Date = '2012-12-10'
group by SID
) t
However, in this case the effect of that is the same as this:
select count(distinct SID) from Test where Date = '2012-12-10'
To iterate through the keys of an object, use a for .. in
loop:
for (var key in json_obj) {
if (json_obj.hasOwnProperty(key)) {
// do something with `key'
}
}
To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.
Removing a property of an object can be done by using the delete
keyword:
var someObj = {
"one": 123,
"two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }
Documentation:
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
As an addition to @C??? answer, make sure the title of the tooltip has not already been set manually in the HTML element. In my case, the span class for the tooltip already had a fixed tittle text, because of this my JQuery function $('[data-toggle="tooltip"]').prop('title', 'your new title');
did not work.
When I removed the title attribute in the HTML span class, the jQuery was working.
So:
<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
<span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top" title="this is my pre-set title text"></span>
</span>
Should becode:
<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
<span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top"></span>
</span>
Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.
x = 'http://test.com/lalala-134-431'
a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"
and partition will divide the string with only first delimiter and will only return 3 values in list
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"
so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"
As said earlier, your code will work unless you have the same classes loaded on two different class loaders. This might happen in case you need multiple versions of the same class in memory at the same time, or you are doing some weird on the fly compilation stuff (as I am).
In this case, if you want to consider these as the same class (which might be reasonable depending on the case), you can match their names to compare them.
public static boolean areClassesQuiteTheSame(Class<?> c1, Class<?> c2) {
// TODO handle nulls maybe?
return c1.getCanonicalName().equals(c2.getCanonicalName());
}
Keep in mind that this comparison will do just what it does: compare class names; I don't think you will be able to cast from one version of a class to the other, and before looking into reflection, you might want to make sure there's a good reason for your classloader mess.
You can find it in Nuget Package Microsoft ASP.NET Web Pages Version 3.2.0
If you have a reference to an earlier version than 3.0.0.0, Delete the reference, add the reference to the correct .dll in your packages folder and make sure "Copy Local" is set to "True" in the properties of the .dll.
Then in your web.config (as mentioned by @MichaelEvanchik)
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages.Razor" PublicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
A fast and simple solution without any 3rd party includes.
public static String strJoin(String[] aArr, String sSep) {
StringBuilder sbStr = new StringBuilder();
for (int i = 0, il = aArr.length; i < il; i++) {
if (i > 0)
sbStr.append(sSep);
sbStr.append(aArr[i]);
}
return sbStr.toString();
}
Go to your tsconfig.json
file and change "noImplicitReturns": false
then add "strictPropertyInitialization": false
to your tsconfig.json
file under "compilerOptions"
property. Here is what my tsconfig.json
file looks like
tsconfig.json
{
...
"compilerOptions": {
....
"noImplicitReturns": false,
....
"strictPropertyInitialization": false
},
"angularCompilerOptions": {
......
}
}
Hope this will help !! Good Luck
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
Looks like all you need is text-align: center;
in ul
Here's what Oracle's documentation has to say:
By default the heap dump is created in a file called java_pid.hprof in the working directory of the VM, as in the example above. You can specify an alternative file name or directory with the
-XX:HeapDumpPath=
option. For example-XX:HeapDumpPath=/disk2/dumps
will cause the heap dump to be generated in the/disk2/dumps
directory.
You can convert the QString type to python string by just using the str
function. Assuming you are not using any Unicode characters you can get a python
string as below:
text = str(combobox1.currentText())
If you are using any unicode characters, you can do:
text = unicode(combobox1.currentText())
I have created little function as workaround solution (inspired by @JohnCulviner plugin):
// creates iframe and form in it with hidden field,
// then submit form with provided data
// url - form url
// data - data to form field
// input_name - form hidden input name
function ajax_download(url, data, input_name) {
var $iframe,
iframe_doc,
iframe_html;
if (($iframe = $('#download_iframe')).length === 0) {
$iframe = $("<iframe id='download_iframe'" +
" style='display: none' src='about:blank'></iframe>"
).appendTo("body");
}
iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
if (iframe_doc.document) {
iframe_doc = iframe_doc.document;
}
iframe_html = "<html><head></head><body><form method='POST' action='" +
url +"'>" +
"<input type=hidden name='" + input_name + "' value='" +
JSON.stringify(data) +"'/></form>" +
"</body></html>";
iframe_doc.open();
iframe_doc.write(iframe_html);
$(iframe_doc).find('form').submit();
}
Demo with click event:
$('#someid').on('click', function() {
ajax_download('/download.action', {'para1': 1, 'para2': 2}, 'dataname');
});
I achieved the goal where I have multiple images to insert in the DB as
INSERT INTO [dbo].[User]
([Name]
,[Image1]
,[Age]
,[Image2]
,[GroupId]
,[GroupName])
VALUES
('Umar'
, (SELECT BulkColumn
FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image1)
,26
,(SELECT BulkColumn
FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image2)
,'Group123'
,'GroupABC')
If you're using a recent Django, changelist 9530 introduced an {% empty %} block, allowing you to write
{% for athlete in athlete_list %}
...
{% empty %}
No athletes
{% endfor %}
Useful when the something that you want to do involves special treatment for lists that might be empty.
Just use:
ViewController *viewController = [[ViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
navController.navigationBarHidden = YES;
[self presentViewController:navController animated:YES completion: nil];
[viewController release];
[navController release];
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
Actually, above codes can be:
>>> sorted(['Some','words','sort','differently'],key=str.lower)
According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
Hi recently looked into this and had issues referencing the named table (list object) within excel
if you place a suffix '$' on the table name all is well in the world
Sub testSQL()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
' Declare variables
strFile = ThisWorkbook.FullName
' construct connection string
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
' create connection and recordset objects
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
' open connection
cn.Open strCon
' construct SQL query
strSQL = "SELECT * FROM [TableName$] where [ColumnHeader] = 'wibble';"
' execute SQL query
rs.Open strSQL, cn
Debug.Print rs.GetString
' close connection
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
As long as strings can be viewed directly as a char array it's going to be really hard to convince me that std::string
represents strings as first class citizens in C++.
Besides, combining allocation and boundedness seems to be a bad idea to me anyways.
You can download in the current directory with a .
:
cd # by default, goes to $HOME
scp me@host:/path/to/file .
or in you HOME
directly with :
scp me@host:/path/to/file ~
My specific error was:
ld: entry point (_main) undefined. for architecture armv7
Which should have been obvious, but it's because main.m
was not include into Compile Sources
under Build Phases
Simply use the .closest()
method: $(this).closest('.li').remove();
It starts with the current element and then climbs up the chain looking for a matching element and stops as soon as it found one.
.parent()
only accesses the direct parent of the element, i.e. div.msg-modification
which does not match .li
. So it never reaches the element you are looking for.
Another solution besides .closest()
(which checks the current element and then climbs up the chain) would be using .parents()
- however, this would have the caveat that it does not stop as soon as it finds a matching element (and it doesn't check the current element but only parent elements). In your case it doesn't really matter but for what you are trying to do .closest()
is the most appropriate method.
NEVER use the same ID for more than one element. It's not allowed and causes very hard-to-debug problems. Remove the id="191"
from the link and, if you need to access the ID in the click handler, use $(this).closest('.li').attr('id')
. Actually it would be even cleaner if you used data-id="123"
and then .data('id')
instead of .attr('id')
to access it (so your element ID does not need to resemble whatever ID the (database?) row has)
Kip's solution should work on Opera and Safari if you change the CSS to:
<style>
#wrap { width: 600px; height: 390px; padding: 0; overflow: hidden; }
#frame { width: 800px; height: 520px; border: 1px solid black; }
#frame {
-ms-zoom: 0.75;
-moz-transform: scale(0.75);
-moz-transform-origin: 0 0;
-o-transform: scale(0.75);
-o-transform-origin: 0 0;
-webkit-transform: scale(0.75);
-webkit-transform-origin: 0 0;
}
</style>
You might also want to specify overflow: hidden on #frame to prevent scrollbars.
EDIT 2016-05-27 - loadRequest
exposes "a universal Cross-Site Scripting vulnerability." Make sure you own every single asset that you load. If you load a bad script, it can load anything it wants.
If you need relative links to work locally, use this:
NSURL *url = [[NSBundle mainBundle] URLForResource:@"my" withExtension:@"html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
The bundle will search all subdirectories of the project to find my.html
. (the directory structure gets flattened at build time)
If my.html
has the tag <img src="some.png">
, the webView will load some.png
from your project.
Take a look on life cycle of Activity
Where
***onCreate()***
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
***onStart()***
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
And you can write your simple class to take a look when these methods call
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private final static String TAG = "TestActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "On Create .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "On Destroy .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "On Pause .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "On Restart .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "On Stop .....");
}
}
Hope this will clear your confusion.
And take a look here for details.
Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.
You could refer to column alias but you need to define it using CROSS/OUTER APPLY
:
SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;
Pros:
WHERE/GROUP BY/ORDER BY
try this, calling the activity in the constructor
public class WebService {
private Activity activity;
public WebService(Activity _activity){
activity=_activity;
helper=new Helper(activity);
}
}
For now I took @Gian's advice & limited the number of records per Workbook to 500k and rolled over the rest to the next Workbook. Seems to be working decent. For the above configuration, it took me about 10 mins per workbook.
You can put the graphic in a pseudo-element with its own dimensional context:
#graphic {
position: relative;
width: 200px;
height: 100px;
}
#graphic::before {
position: absolute;
content: '';
z-index: -1;
width: 200px;
height: 50px;
background-image: url(image.jpg);
}
#graphic {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
position: relative;_x000D_
}_x000D_
#graphic::before {_x000D_
content: '';_x000D_
_x000D_
position: absolute;_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
z-index: -1;_x000D_
_x000D_
background-image: url(http://placehold.it/500x500/); /* Image is 500px by 500px, but only 200px by 50px is showing. */_x000D_
}
_x000D_
<div id="graphic">lorem ipsum</div>
_x000D_
Browser support is good, but if you need to support IE8, use a single colon :before
. IE has no support for either syntax in versions prior to that.
more generally, for standard errors on any other parameter, you can use the boot package for bootstrap simulations (or write them on your own)
Working example here at : http://jsfiddle.net/tQ2CZ/1/
HTML
<div id="video_container">
<video poster="http://media.w3.org/2010/05/sintel/poster.png" preload="none" controls="" id="video" tabindex="0">
<source type="video/mp4" src="http://media.w3.org/2010/05/sintel/trailer.mp4" id="mp4"></source>
<source type="video/webm" src="http://media.w3.org/2010/05/sintel/trailer.webm" id="webm"></source>
<source type="video/ogg" src="http://media.w3.org/2010/05/sintel/trailer.ogv" id="ogv"></source>
<p>Your user agent does not support the HTML5 Video element.</p>
</video>
</div>
<div>Current Time : <span id="currentTime">0</span></div>
<div>Total time : <span id="totalTime">0</span></div>
JS
$(function(){
$('#currentTime').html($('#video_container').find('video').get(0).load());
$('#currentTime').html($('#video_container').find('video').get(0).play());
})
setInterval(function(){
$('#currentTime').html($('#video_container').find('video').get(0).currentTime);
$('#totalTime').html($('#video_container').find('video').get(0).duration);
},500)
try this
Jobs
select s.name,l.name
from msdb..sysjobs s
left join master.sys.syslogins l on s.owner_sid = l.sid
Packages
select s.name,l.name
from msdb..sysssispackages s
left join master.sys.syslogins l on s.ownersid = l.sid
You could try adding an<hr>
and styling that. Its a minimal markup change but seems to need less css so that might do the trick.
fiddle:
For v4.0.7 You can increase the height by overriding CSS classes like this example:
.select2-container .select2-selection--single {
height: 36px;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
line-height: 36px;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
height: 36px;
}
Change the line where you print the output to:
printf("\nmaximum of %d and %d is = %d",a,b,c);
See the docs here
You can use PreferredSize
and flexibleSpace
for it:
appBar: PreferredSize(
preferredSize: Size.fromHeight(100.0),
child: AppBar(
automaticallyImplyLeading: false, // hides leading widget
flexibleSpace: SomeWidget(),
)
),
This way you can keep the elevation
of AppBar
for keeping its shadow visible and have custom height, which is what I was just looking for. You do have to set the spacing in SomeWidget
, though.
Internally, Javascript strings are all Unicode (actually UCS-2, a subset of UTF-16).
If you're retrieving the JSON files separately via AJAX, then you only need to make sure that the JSON files are served with the correct Content-Type and charset: Content-Type: application/json; charset="utf-8"
). If you do that, jQuery should already have interpreted them properly by the time you access the deserialized objects.
Could you post an example of the code you’re using to retrieve the JSON objects?
Bootstrap 2.3 has utility classes text-left
, text-right
, and text-center
, but they do not work in table cells. Until Bootstrap 3.0 is released (where they have fixed the issue) and I am able to make the switch, I have added this to my site CSS that is loaded after bootstrap.css
:
.text-right {
text-align: right !important;
}
.text-center {
text-align: center !important;
}
.text-left {
text-align: left !important;
}
Information from the Official Adobe site about this issue
The issue is when you embed a youtube link:
https://www.youtube.com/embed/kRvL6K8SEgY
in an iFrame, the default wmode is windowed which essentially gives it a z-index greater then everything else and it will overlay over anything.
Try appending this GET parameter to your URL:
wmode=opaque
like so:
https://www.youtube.com/embed/kRvL6K8SEgY?wmode=opaque
Make sure its the first parameter in the URL. Other parameters must go after
In the iframe tag:
Example:
<iframe class="youtube-player" type="text/html" width="520" height="330" src="http://www.youtube.com/embed/NWHfY_lvKIQ?wmode=opaque" frameborder="0"></iframe>
I split var all over the places, the only questionable places for me are internal short types, e.g. I prefer int i = 3;
over var i = 3;
In laravel 6 the latest one can easily add in the "APP/user.php" model:
/**
* The storage format of the model's date columns.
*
* @var string
*/
protected $dateFormat = 'U';
And in schema one can add
$table->integer('created_at')->nullable();
$table->integer('updated_at')->nullable();
What you want is:
Foo *array[10]; // array of 10 Foo pointers
Not to be confused with:
Foo (*array)[10]; // pointer to array of 10 Foos
In either case, nothing will be automatically initialized because these represent pointers to Foos that have yet to be assigned to something (e.g. with new).
I finally "got" pointer/array declaration syntax in C when I realized that it describes how you access the base type. Foo *array[5][10];
means that *array[0..4][0..9]
(subscript on an array of 5 items, then subscript on an array of 10 items, then dereference as a pointer) will access a Foo object (note that []
has higher precedence than *
).
This seems backwards. You would think that int array[5][10];
(a.k.a. int (array[5])[10];
) is an array of 10 int array[5]
. Suppose this were the case. Then you would access the last element of the array by saying array[9][4]
. Doesn't that look backwards too? Because a C array declaration is a pattern indicating how to get to the base type (rather than a composition of array expressions like one might expect), array declarations and code using arrays don't have to be flipflopped.
We have that problem quite often, but only with references to C++/CLI projects from C# projects. It's obviously a bug deep down in Visual Studio that Microsoft decided not to fix, because it's 'too complex' and they promised an overhaul of the C++ build system which is now targeted for Visual Studio 2010.
That was some time ago, and maybe the fix even went into Visual Studio 2008; I didn't follow up on it any more. However, our typical workaround was
To add .pch file-
1) Add new .pch file to your project->New file->other->PCH file
2) Goto your project's build setting.
3) Search "prefix header". You can find that under Apple LLVM.
4) Paste this in the field $(SRCROOT)/yourPrefixHeaderFileName.pch
5) Clean and build the project. That's it!!!
If you want to do anything else during the iteration, it may be nice to get both the index (which guarantees you being able to reference it, for example if you have a list of dicts) and the actual list item contents.
inlist = [{'field1':10, 'field2':20}, {'field1':30, 'field2':15}]
for idx, i in enumerate(inlist):
do some stuff with i['field1']
if somecondition:
xlist.append(idx)
for i in reversed(xlist): del inlist[i]
enumerate
gives you access to the item and the index at once. reversed
is so that the indices that you're going to later delete don't change on you.
LinearLayout supports assigning a weight to individual children. This attribute assigns an "importance" value to a view, and allows it to expand to fill any remaining space in the parent view. Default weight is zero
calculation to assign any Remaining/Extra space between child. (not the total space)
space assign to child = (child individual weight) / (sum of weight of every child in Linear Layout)
Example (1): if there are three text boxes and two of them declare a weight of 1, while the third one is given no weight (0), then Remaining/Extra space assign to
1st text box = 1/(1+1+0)
2nd text box = 1/(1+1+0)
3rd text box = 0/(1+1+0)
Example (2) : let's say we have a text label and two text edit elements in a horizontal row. The label has no layout_weight specified, so it takes up the minimum space required to render. If the layout_weight of each of the two text edit elements is set to 1, the remaining width in the parent layout will be split equally between them (because we claim they are equally important).
calculation :
1st label = 0/(0+1+1)
2nd text box = 1/(0+1+1)
3rd text box = 1/(0+1+1)
If the first one text box has a layout_weight of 1 and the second text box has a layout_weight of 2, then one third of the remaining space will be given to the first, and two thirds to the second (because we claim the second one is more important).
calculation :
1st label = 0/(0+1+2)
2nd text box = 1/(0+1+2)
3rd text box = 2/(0+1+2)
Slightly modified (bastardized?) version of the answer by Tod Thomson as a static function rather than a separate class (I wanted to be able to call it in a WebForm viewbinding from a viewutils class I already had included).
public static bool isDebugging() {
bool debugging = false;
WellAreWe(ref debugging);
return debugging;
}
[Conditional("DEBUG")]
private static void WellAreWe(ref bool debugging)
{
debugging = true;
}
if in string:
string yourVar = yourTextBoxname.Text;
if in numbers:
int yourVar = int.Parse(yourTextBoxname.Text);
The issue with the conversion (the reason it's giving you a ffffff at the end) is because your hex integer (that you are using the & binary operator with) is interpreted as being signed. Cast it to an unsigned integer, and you'll be fine.
I think that people making decisions simply forgot about complex values, matrix algebra, set theory and other cases when overloading would allow to use the standard notation without building everything into the language. Anyway, only mathematically oriented software really benefits from such features. A generic customer application almost never needs them.
They arguments about the unnecessary obfuscation are obviously valid when a programmer defines some program-specific operator where it could be the function instead. A name of the function, when clearly visible, provides the hint that it does. Operator is a function without the readable name.
Java is generally designed about philosophy that some extra verbosity is not bad as it makes the code more readable. Constructs that do the same just have less code to type in used to be called a "syntax sugar" in the past. This is very different from the Python philosophy, for instance, where shorter is near always seen as better, even if providing less context for the second reader.
I just had the same problem with a cookie which was set to expire on "Browsing session end".
Unfortunately it did not so I played a bit with the settings of the browser.
Turned out that the feature that remembers the opened tabs when the browser is closed was the root of the problem. (The feature is named "On startup" - "Continue where I left off". At least on the current version of Chrome).
This also happens with Opera and Firefox.
Adding to the answer from Ignacio Vazquez-Abrams. This will allow for the + sign to precede the integer, and it will allow any number of zeros as decimal points. For example, this will allow +45.00000000 to be considered an integer.
However, $1 must be formatted to contain a decimal point. 45 is not considered an integer here, but 45.0 is.
if [[ $1 =~ ^-?[0-9]+.?[0]+$ ]]; then
echo "yes, this is an integer"
elif [[ $1 =~ ^\+?[0-9]+.?[0]+$ ]]; then
echo "yes, this is an integer"
else
echo "no, this is not an integer"
fi
I ran a benchmark and . These benchmarks were run on a MacBook Pro 2010 13" (Core2 Duo 2.66GHz, 4GB 1067MHz DDR3 RAM, Mac OS X 10.6.5).sorted(lst, reverse=True) == lst
was the fastest for long lists, and all(l[i] >= l[i+1] for i in xrange(len(l)-1))
was the fastest for short lists
UPDATE: I revised the script so that you can run it directly on your own system. The previous version had bugs. Also, I have added both sorted and unsorted inputs.
all(l[i] >= l[i+1] for i in xrange(len(l)-1))
sorted(l, reverse=True) == l
all(l[i] >= l[i+1] for i in xrange(len(l)-1))
all(l[i] >= l[i+1] for i in xrange(len(l)-1))
So in most cases there is a clear winner.
UPDATE: aaronsterling's answers (#6 and #7) are actually the fastest in all cases. #7 is the fastest because it doesn't have a layer of indirection to lookup the key.
#!/usr/bin/env python
import itertools
import time
def benchmark(f, *args):
t1 = time.time()
for i in xrange(1000000):
f(*args)
t2 = time.time()
return t2-t1
L1 = range(4, 0, -1)
L2 = range(100, 0, -1)
L3 = range(0, 4)
L4 = range(0, 100)
# 1.
def isNonIncreasing(l, key=lambda x,y: x >= y):
return all(key(l[i],l[i+1]) for i in xrange(len(l)-1))
print benchmark(isNonIncreasing, L1) # 2.47253704071
print benchmark(isNonIncreasing, L2) # 34.5398209095
print benchmark(isNonIncreasing, L3) # 2.1916718483
print benchmark(isNonIncreasing, L4) # 2.19576501846
# 2.
def isNonIncreasing(l):
return all(l[i] >= l[i+1] for i in xrange(len(l)-1))
print benchmark(isNonIncreasing, L1) # 1.86919999123
print benchmark(isNonIncreasing, L2) # 21.8603689671
print benchmark(isNonIncreasing, L3) # 1.95684289932
print benchmark(isNonIncreasing, L4) # 1.95272517204
# 3.
def isNonIncreasing(l, key=lambda x,y: x >= y):
return all(key(a,b) for (a,b) in itertools.izip(l[:-1],l[1:]))
print benchmark(isNonIncreasing, L1) # 2.65468883514
print benchmark(isNonIncreasing, L2) # 29.7504849434
print benchmark(isNonIncreasing, L3) # 2.78062295914
print benchmark(isNonIncreasing, L4) # 3.73436689377
# 4.
def isNonIncreasing(l):
return all(a >= b for (a,b) in itertools.izip(l[:-1],l[1:]))
print benchmark(isNonIncreasing, L1) # 2.06947803497
print benchmark(isNonIncreasing, L2) # 15.6351969242
print benchmark(isNonIncreasing, L3) # 2.45671010017
print benchmark(isNonIncreasing, L4) # 3.48461818695
# 5.
def isNonIncreasing(l):
return sorted(l, reverse=True) == l
print benchmark(isNonIncreasing, L1) # 2.01579380035
print benchmark(isNonIncreasing, L2) # 5.44593787193
print benchmark(isNonIncreasing, L3) # 2.01813793182
print benchmark(isNonIncreasing, L4) # 4.97615599632
# 6.
def isNonIncreasing(l, key=lambda x, y: x >= y):
for i, el in enumerate(l[1:]):
if key(el, l[i-1]):
return False
return True
print benchmark(isNonIncreasing, L1) # 1.06842684746
print benchmark(isNonIncreasing, L2) # 1.67291283607
print benchmark(isNonIncreasing, L3) # 1.39491200447
print benchmark(isNonIncreasing, L4) # 1.80557894707
# 7.
def isNonIncreasing(l):
for i, el in enumerate(l[1:]):
if el >= l[i-1]:
return False
return True
print benchmark(isNonIncreasing, L1) # 0.883186101913
print benchmark(isNonIncreasing, L2) # 1.42852401733
print benchmark(isNonIncreasing, L3) # 1.09229516983
print benchmark(isNonIncreasing, L4) # 1.59502696991
Here's a benchmark to compare a Go for
statement with a ForClause and a Go range
statement using the iter
package.
iter_test.go
package main
import (
"testing"
"github.com/bradfitz/iter"
)
const loops = 1e6
func BenchmarkForClause(b *testing.B) {
b.ReportAllocs()
j := 0
for i := 0; i < b.N; i++ {
for j = 0; j < loops; j++ {
j = j
}
}
_ = j
}
func BenchmarkRangeIter(b *testing.B) {
b.ReportAllocs()
j := 0
for i := 0; i < b.N; i++ {
for j = range iter.N(loops) {
j = j
}
}
_ = j
}
// It does not cause any allocations.
func N(n int) []struct{} {
return make([]struct{}, n)
}
func BenchmarkIterAllocs(b *testing.B) {
b.ReportAllocs()
var n []struct{}
for i := 0; i < b.N; i++ {
n = iter.N(loops)
}
_ = n
}
Output:
$ go test -bench=. -run=.
testing: warning: no tests to run
PASS
BenchmarkForClause 2000 1260356 ns/op 0 B/op 0 allocs/op
BenchmarkRangeIter 2000 1257312 ns/op 0 B/op 0 allocs/op
BenchmarkIterAllocs 20000000 82.2 ns/op 0 B/op 0 allocs/op
ok so/test 7.026s
$
I created a solution using pipes, eval and signal.
parent() {
if [ -z "$G_EVAL_FD" ]; then
die 1 "Rode primeiro parent_setup no processo pai"
fi
if [ $(ppid) = "$$" ]; then
"$@"
else
kill -SIGUSR1 $$
echo "$@">&$G_EVAL_FD
fi
}
parent_setup() {
G_EVAL_FD=99
tempfile=$(mktemp -u)
mkfifo "$tempfile"
eval "exec $G_EVAL_FD<>'$tempfile'"
rm -f "$tempfile"
trap "read CMD <&$G_EVAL_FD; eval \"\$CMD\"" USR1
}
parent_setup #on parent shell context
( A=1 ); echo $A # prints nothing
( parent A=1 ); echo $A # prints 1
It might work with any command.
please modify your router.module.ts as:
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree',
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
},
{
path: '',
redirectTo: 'two',
pathMatch: 'full'
}
]
},];
and in your component1.html
<h3>In One</h3>
<nav>
<a routerLink="/two" class="dash-item">...Go to Two...</a>
<a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
<a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>
<router-outlet></router-outlet> // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
I prefer Scanner
because it doesn't throw checked exceptions and therefore it's usage results in a more streamlined code.
Although the solution by Nik Reiman DOES work, I found it not to be an optimal solution for what I wanted to do. Using the divider to set the margins had the problem that the divider will no longer be visible so you can not use it to show a clear boundary between your items. Also, it does not add more "clickable area" to each item thus if you want to make your items clickable and your items are thin, it will be very hard for anyone to click on an item as the height added by the divider is not part of an item.
Fortunately I found a better solution that allows you to both show dividers and allows you to adjust the height of each item using not margins but padding. Here is an example:
ListView
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
ListItem
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="10dp"
android:paddingTop="10dp" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Item"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
To store values in shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
To retrieve values from shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");
When you do the for/in loop you put up first, i is the property name. So you have the property name, i, and access the value by doing myObject[i].
It's called setuptools. You run it with the "easy_install" command.
You can find the directory at http://pypi.python.org/
Here's a function that is also based on cloneNode
, but with an option to clone only the parent node and move all the children (to preserve their event listeners):
function recreateNode(el, withChildren) {
if (withChildren) {
el.parentNode.replaceChild(el.cloneNode(true), el);
}
else {
var newEl = el.cloneNode(false);
while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
el.parentNode.replaceChild(newEl, el);
}
}
Remove event listeners on one element:
recreateNode(document.getElementById("btn"));
Remove event listeners on an element and all of its children:
recreateNode(document.getElementById("list"), true);
If you need to keep the object itself and therefore can't use cloneNode
, then you have to wrap the addEventListener
function and track the listener list by yourself, like in this answer.
I use this:
public static <T> T getBean(Class<T> clazz) {
try {
String beanName = getBeanName(clazz);
FacesContext facesContext = FacesContext.getCurrentInstance();
return facesContext.getApplication().evaluateExpressionGet(facesContext, "#{" + beanName + "}", clazz);
//return facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, nomeBean);
} catch (Exception ex) {
return null;
}
}
public static <T> String getBeanName(Class<T> clazz) {
ManagedBean managedBean = clazz.getAnnotation(ManagedBean.class);
String beanName = managedBean.name();
if (StringHelper.isNullOrEmpty(beanName)) {
beanName = clazz.getSimpleName();
beanName = Character.toLowerCase(beanName.charAt(0)) + beanName.substring(1);
}
return beanName;
}
And then call:
MyManageBean bean = getBean(MyManageBean.class);
This way you can refactor your code and track usages without problems.
I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:
In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:
The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.
So Hibernate as well behaves like Ashish Agarwal stated above for JPA:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
(see JPA 2.1 Spec)
I had the same problem with Debian 8. I fixed it by restarting the system. It seems that the error can occur if the kernel image was updated and the system was not restarted thereafter.
When using numbers as the key, I suppose you could also try this:
Map<Long, String> map = new HashMap<>();
map.put(4L, "The First");
map.put(6L, "The Second");
map.put(11L, "The Last");
long lastKey = 0;
//you entered Map<Long, String> entry
for (Map.Entry<Long, String> entry : map.entrySet()) {
lastKey = entry.getKey();
}
System.out.println(lastKey); // 11
If you're going to run a little console app, you may as well install clrver.exe
from the .NET SDK. I don't think you can get cleaner than that. This isn't my answer (but I happen to agree), I found it here.
You can use a closure for this:
func doif(b bool, f1, f2 func()) {
switch{
case b:
f1()
case !b:
f2()
}
}
func dothis() { fmt.Println("Condition is true") }
func dothat() { fmt.Println("Condition is false") }
func main () {
condition := true
doif(condition, func() { dothis() }, func() { dothat() })
}
The only gripe I have with the closure syntax in Go is there is no alias for the default zero parameter zero return function, then it would be much nicer (think like how you declare map, array and slice literals with just a type name).
Or even the shorter version, as a commenter just suggested:
func doif(b bool, f1, f2 func()) {
switch{
case b:
f1()
case !b:
f2()
}
}
func dothis() { fmt.Println("Condition is true") }
func dothat() { fmt.Println("Condition is false") }
func main () {
condition := true
doif(condition, dothis, dothat)
}
You would still need to use a closure if you needed to give parameters to the functions. This could be obviated in the case of passing methods rather than just functions I think, where the parameters are the struct associated with the methods.
Google says to check out getenv():
Returns an unmodifiable string map view of the current system environment.
I'm not sure how system variables differ from environment variables, however, so if you could clarify I could help out more.
Reg file
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Console]
"CodePage"=dword:fde9
Command Prompt
REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 0xfde9
PowerShell
sp -t d HKCU:\Console CodePage 0xfde9
Cygwin
regtool set /user/Console/CodePage 0xfde9
According to the latest pandas documentation you can read a csv file selecting only the columns which you want to read.
import pandas as pd
df = pd.read_csv('some_data.csv', usecols = ['col1','col2'], low_memory = True)
Here we use usecols
which reads only selected columns in a dataframe.
We are using low_memory
so that we Internally process the file in chunks.
The simple solution is to avoid creating an array before piping to Out-File. Rule #1 of PowerShell is that the comma is a special delimiter, and the default behavior is to create an array. Concatenation is done like this.
$computer + "," + $Speed + "," + $Regcheck | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200
This creates an array of three items.
$computer,$Speed,$Regcheck
FYKJ
100
YES
vs. concatenation of three items separated by commas.
$computer + "," + $Speed + "," + $Regcheck
FYKJ,100,YES
import os
os.system("echo 'hello world'")
This should work. I do not know how to print the output into the python Shell.
Iterate through the GridView rows and make the cells of your target columns invisible. In this example I want to keeps columns 4-6 visible as is, so we skip those:
foreach (GridViewRow row in yourGridView.Rows)
{
for (int i = 0; i < rows.Cells.Count; i++)
{
switch (i)
{
case 4:
case 5:
case 6:
continue;
}
row.Cells[i].Visible = false;
};
};
Then you will need to remove the column headers separately (keep in mind that removing header cells changes the length of the GridView after each removal):
grdReportRole.HeaderRow.Cells.RemoveAt(0);
If the URL is https, like used for Amazon S3, then use getURL
json <- fromJSON(getURL('https://s3.amazonaws.com/bucket/my.json'))
You can set value for all case.
demoImage.getLayoutParams().height = 150;
demoImage.getLayoutParams().width = 150;
demoImage.setScaleType(ImageView.ScaleType.FIT_XY);
If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
See: http://msdn.microsoft.com/en-us/data/dn456843.aspx
use context.Database.BeginTransaction.
using (var context = new BloggingContext()) { using (var dbContextTransaction = context.Database.BeginTransaction()) { try { context.Database.ExecuteSqlCommand( @"UPDATE Blogs SET Rating = 5" + " WHERE Name LIKE '%Entity Framework%'" ); var query = context.Posts.Where(p => p.Blog.Rating >= 5); foreach (var post in query) { post.Title += "[Cool Blog]"; } context.SaveChanges(); dbContextTransaction.Commit(); } catch (Exception) { dbContextTransaction.Rollback(); //Required according to MSDN article throw; //Not in MSDN article, but recommended so the exception still bubbles up } } }
SELECT
t.A,
t.B,
t.C,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t
See working example at SQLFiddle
Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1))
for, e.g., OVER (ORDER BY t.C)
, like in a normal ORDER BY
clause.
Public SUB test()
Dim mdate As Date
mdate = now()
MsgBox (Round(CDbl(mdate), 0))
End SUB
i created a custom dialog API. check it out here https://github.com/MarkMyWord03/CustomDialog. It supports message and confirmation box. input and option dialog just like in joptionpane will be implemented soon.
Sample Error Dialog from CUstomDialog API: CustomDialog Error Message
Yes, on Arrays.asList
, returning a fixed-size list.
Other than using a linked list, simply use addAll
method list.
Example:
String idList = "123,222,333,444";
List<String> parentRecepeIdList = new ArrayList<String>();
parentRecepeIdList.addAll(Arrays.asList(idList.split(",")));
parentRecepeIdList.add("555");
You need to give relative
or absolute
or fixed
positioning to your container (#shop
) and set its zIndex
to say 100.
You also need to give say relative
positioning to your elements with the class content
and lower zIndex
say 97.
Do the above-mentioned with your images too and set their zIndex
to 91.
And then position your button higher by setting its position to absolute
and zIndex
to 95
See the DEMO
HTML
<div id="shop">
<div class="content"> Counter-Strike 1.6 Steam
<img src="http://www.openvms.org/images/samples/130x130.gif">
<a href="#"><span class='span'><span></a>
</div>
<div class="content"> Counter-Strike 1.6 Steam
<img src="http://www.openvms.org/images/samples/130x130.gif">
<a href="#"><span class='span'><span></a>
</div>
</div>
CSS
#shop{
background-image: url("images/shop_bg.png");
background-repeat: repeat-x;
height:121px;
width: 984px;
margin-left: 20px;
margin-top: 13px;
position:relative;
z-index:100
}
#shop .content{
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
z-index:97
}
img{
position:relative;
z-index:91
}
.span{
width:70px;
height:40px;
border:1px solid red;
position:absolute;
z-index:95;
right:60px;
bottom:-20px;
}
<a href="#"><button type="button" class="btn btn-info btn-block regular-link"> <span class="text">Create New Board</span></button></a>
We can use btn-block for automatic responsive.
If you are working in XAMPP and your query of drop database doesn't work then you can go to the operations tag where you find the column (drop the database(drop)), click that button and your database will be deleted.
Facebook uses the LAMP stack, so if you want to get a career with them you're going to want to focus on that. In addition they often have C++ and/or Java listed in their requirements as well.
One of the postings includes the following requirements:
Another:
Another:
http://www.facebook.com/careers/#!/careers/department.php?dept=engineering
Also, do any other social networking sites use the same language?
Some other companys that use PHP/LAMP Stack:
$startinfo = new-object System.Diagnostics.ProcessStartInfo
$startinfo.FileName = "explorer.exe"
$startinfo.WorkingDirectory = 'D:\foldername'
[System.Diagnostics.Process]::Start($startinfo)
Hope this helps
Probably the easiest to hide a div and show a div in PHP based on a variables and the operator.
<?php
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
?>
<html>
<?php if($numrows > null){ ?>
no meow :-(
<?php } ?>
<?php if($numrows < null){ ?>
lots of meow
<?php } ?>
</html>
Here is my original code before adding your requirements:
<?php
$address = 'meow';
?>
<?php if($address == null){ ?>
no meow :-(
<?php } ?>
<?php if($address != null){ ?>
lots of meow
<?php } ?>
There is a much easier way to compile and run C code using GCC, no configuration needed:
Ctrl+Alt+N
, or press F1
and then select/type Run Code
, or right click the Text Editor and then click Run Code
in context menu, the code will be compiled and run, and the output will be shown in the Output Window.Moreover you could update the config in settings.json using different C compilers as you want, the default config for C is as below:
"code-runner.executorMap": {
"c": "gcc $fullFileName && ./a.out"
}
var array = [[1, "grape", 42], [2, "fruit", 9]];
array.sort(function(a, b)
{
// a and b will here be two objects from the array
// thus a[1] and b[1] will equal the names
// if they are equal, return 0 (no sorting)
if (a[1] == b[1]) { return 0; }
if (a[1] > b[1])
{
// if a should come after b, return 1
return 1;
}
else
{
// if b should come after a, return -1
return -1;
}
});
The sort
function takes an additional argument, a function that takes two arguments. This function should return -1
, 0
or 1
depending on which of the two arguments should come first in the sorting. More info.
I also fixed a syntax error in your multidimensional array.
To get the version of JVM currently running the program
System.out.println(Runtime.class.getPackage().getImplementationVersion());
Here's a general procedure for producing a random number in a specified range:
int randInRange(int min, int max)
{
return min + (int) (rand() / (double) (RAND_MAX + 1) * (max - min + 1));
}
Depending on the PRNG algorithm being used, the %
operator may result in a very non-random sequence of numbers.
In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :
Take out the MONTHS from your case, and remove the brackets... like this:
CASE
WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
ELSE 'NOTHING'
END AS 'MONTHS'
You can think of this as being equivalent to:
CASE TRUE
WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
ELSE 'NOTHING'
END AS 'MONTHS'
This will bring back totals per property and type
SELECT PropertyID,
TYPE,
SUM(Amount)
FROM yourTable
GROUP BY PropertyID,
TYPE
This will bring back only active values
SELECT PropertyID,
TYPE,
SUM(Amount)
FROM yourTable
WHERE EndDate IS NULL
GROUP BY PropertyID,
TYPE
and this will bring back totals for properties
SELECT PropertyID,
SUM(Amount)
FROM yourTable
WHERE EndDate IS NULL
GROUP BY PropertyID
......
Mutex and Semaphore didn't work in my case (I tried them as suggested, but it didn't do the trick in the application I developed). The answer abramlimpin provided worked for me, after I made a slight modification.
This is how I got it working finally. First, I created some helper functions:
public static class Ext
{
private static string AssemblyFileName(this Assembly myAssembly)
{
string strLoc = myAssembly.Location;
FileSystemInfo fileInfo = new FileInfo(strLoc);
string sExeName = fileInfo.Name;
return sExeName;
}
private static int HowManyTimesIsProcessRunning(string name)
{
int count = 0;
name = name.ToLowerInvariant().Trim().Replace(".exe", "");
foreach (Process clsProcess in Process.GetProcesses())
{
var processName = clsProcess.ProcessName.ToLowerInvariant().Trim();
// System.Diagnostics.Debug.WriteLine(processName);
if (processName.Contains(name))
{
count++;
};
};
return count;
}
public static int HowManyTimesIsAssemblyRunning(this Assembly myAssembly)
{
var fileName = AssemblyFileName(myAssembly);
return HowManyTimesIsProcessRunning(fileName);
}
}
Then, I added the following to the main method:
[STAThread]
static void Main()
{
const string appName = "Name of your app";
// Check number of instances running:
// If more than 1 instance, cancel this one.
// Additionally, if it is the 2nd invocation, show a message and exit.
var numberOfAppInstances = Assembly.GetExecutingAssembly().HowManyTimesIsAssemblyRunning();
if (numberOfAppInstances == 2)
{
MessageBox.Show("The application is already running!
+"\nClick OK to close this dialog, then switch to the application by using WIN + TAB keys.",
appName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
};
if (numberOfAppInstances >= 2)
{
return;
};
}
If you invoke the application a 3rd, 4th ... time, it does not show the warning any more and just exits immediately.
If you don't care about rouding, just convert the number to a string, then remove everything after the period including the period. This works whether there is a decimal or not.
const sEpoch = ((+new Date()) / 1000).toString();
const formattedEpoch = sEpoch.split('.')[0];
Alternatively, create a figure()
object using the figsize
argument and then use add_subplot
to add your subplots. E.g.
import matplotlib.pyplot as plt
import numpy as np
f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')
Benefits of this method are that the syntax is closer to calls of subplot()
instead of subplots()
. E.g. subplots doesn't seem to support using a GridSpec
for controlling the spacing of the subplots, but both subplot()
and add_subplot()
do.
I found a solution to my problem. You could go to this site:
https://developers.facebook.com/tools/debug
...then put in the URL of the page you want to share, and click "debug". It will automatically extract all the info on your meta tags and also clear the cache.
if you just need to load script dont do as bellow
$(document.body).html('<script type="text/javascript" src="/json.js" async="async"><\/script>');
Try this
var scriptEl = document.createElement('SCRIPT');
scriptEl.src = "/module/script/form?_t="+(new Date()).getTime();
//$('#holder').append(scriptEl) // <--- create warning
document.body.appendChild(scriptEl);
The first visible character is '!' according to ASCII table.And the last one is '~' So "!file.doc" or "~file.doc' will be the top one depending your ranking order. You can check the ascii table here: http://www.asciitable.com/
Edit: This answer is based on the opinion of the author and not facts.
run ng version
then simply check the version of angular core package.
@angular/cli: 1.2.6
node: 8.11.1
os: win32 x64
@angular/animations: 4.3.2
@angular/common: 4.3.2
@angular/compiler: 4.3.2
**@angular/core: 4.3.2**
@angular/forms: 4.3.2
Quoting this link: http://steveswanson.wordpress.com/2009/04/21/exporting-and-importing-an-individual-mysql-table/
To export the table run the following command from the command line:
mysqldump -p --user=username dbname tableName > tableName.sql
This will export the tableName to the file tableName.sql.
To import the table run the following command from the command line:
mysql -u username -p -D dbname < tableName.sql
The path to the tableName.sql needs to be prepended with the absolute path to that file. At this point the table will be imported into the DB.
Do everything suggested by ziesemer.
You may also want to remove from the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\<any Ora* drivers> keys
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers<any Ora* driver> values
So they no longer appear in the "ODBC Drivers that are installed on your system" in ODBC Data Source Administrator
Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.
I think the prop method is more convenient when it comes to boolean attribute. http://api.jquery.com/prop/
Just use this code, If you want values of [Category] and [CreationDate] columns
SELECT [Category], MAX([CreationDate]) FROM [MonitoringJob]
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC
Or use this code, If you want only values of [Category] column.
SELECT [Category] FROM [MonitoringJob]
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC
You'll have all the distinct records what ever you want.
I have personally found the dzone cheatsheet on core java to be really handy in the beginning. However the needs change as we grow and get used to things.
There are a few listed (at the end of the post) in on this java learning resources article too
For the most practical use, in recent past I have found Java API doc to be the best place to cheat code and learn new api. This helps specially when you want to focus on latest version of java.
mkyong - is one my fav places to cheat a lot of code for quick start - http://www.mkyong.com/
And last but not the least, Stackoverflow is king of all small handy code snippets. Just google a stuff you are trying and there is a chance that a page will be top of search results, most of my google search results end at stackoverflow. Many of the common questions are available here - https://stackoverflow.com/questions/tagged/java?sort=frequent
Simply, to enforce JAVA version to Ant in Eclipse:
Use RunAs option on Ant file then select External Tool Configuration in JRE tab define your JDK/JRE version you want to use.
SELECT last_value, increment_by from "other_schema".id_seq;
for adding a seq to a column where the schema is not public try this.
nextval('"other_schema".id_seq'::regclass)
I got this after upgrading to ruby 2.1.0. My PATH
was set in my login script to include .gem/ruby/2.0.0/bin
. Updating the version number fixed it.
Regex regex = new Regex(@"\W+");
string outputString = regex.Replace(inputString, " ");
If you are using Python/Django it's pretty easy:
create two databases in settings.py (like here https://docs.djangoproject.com/en/1.11/topics/db/multi-db/)
then just do like this:
objlist = ModelObject.objects.using('sqlite').all()
for obj in objlist:
obj.save(using='mysql')
It seeems like you want to remove ONLY columns with ALL NA
s, leaving columns with some rows that do have NA
s. I would do this (but I am sure there is an efficient vectorised soution:
#set seed for reproducibility
set.seed <- 103
df <- data.frame( id = 1:10 , nas = rep( NA , 10 ) , vals = sample( c( 1:3 , NA ) , 10 , repl = TRUE ) )
df
# id nas vals
# 1 1 NA NA
# 2 2 NA 2
# 3 3 NA 1
# 4 4 NA 2
# 5 5 NA 2
# 6 6 NA 3
# 7 7 NA 2
# 8 8 NA 3
# 9 9 NA 3
# 10 10 NA 2
#Use this command to remove columns that are entirely NA values, it will elave columns where only some vlaues are NA
df[ , ! apply( df , 2 , function(x) all(is.na(x)) ) ]
# id vals
# 1 1 NA
# 2 2 2
# 3 3 1
# 4 4 2
# 5 5 2
# 6 6 3
# 7 7 2
# 8 8 3
# 9 9 3
# 10 10 2
If you find yourself in the situation where you want to remove columns that have any NA
values you can simply change the all
command above to any
.
add a repository,
sudo apt-add-repository ppa:maarten-fonville/android-studio
sudo apt-get update
Then install using the command below:
sudo apt-get install android-studio
For all newbie guys searching for some hint about currency conversion, take a look at this link. Datavoila
It helped med a lot regarding my own project in C#. Just in case the site disappears, I'll add the code below. Just add the below steps to your own project. Sorry about the formatting.
const string fromCurrency = "USD";
const string toCurrency = "EUR";
const double amount = 49.95;
// For other currency symbols see http://finance.yahoo.com/currency-converter/
// Clear the output editor //optional use, AFAIK
Output.Clear();
// Construct URL to query the Yahoo! Finance API
const string urlPattern = "http://finance.yahoo.com/d/quotes.csv?s={0}{1}=X&f=l1";
string url = String.Format(urlPattern, fromCurrency, toCurrency);
// Get response as string
string response = new WebClient().DownloadString(url);
// Convert string to number
double exchangeRate =
double.Parse(response, System.Globalization.CultureInfo.InvariantCulture);
// Output the result
Output.Text = String.Format("{0} {1} = {2} {3}",
amount, fromCurrency,
amount * exchangeRate, toCurrency);
If you're getting this, you may have forgotten to put #include <thread>
at the beginning of your file. OP's signature seems like it should work.
public class WordCount {
public static void main(String[] args) {
// TODO Auto-generated method stub
String scentence = "This is a treeis isis is is is";
String word = "is";
int wordCount = 0;
for(int i =0;i<scentence.length();i++){
if(word.charAt(0) == scentence.charAt(i)){
if(i>0){
if(scentence.charAt(i-1) == ' '){
if(i+word.length()<scentence.length()){
if(scentence.charAt(i+word.length()) != ' '){
continue;}
}
}
else{
continue;
}
}
int count = 1;
for(int j=1 ; j<word.length();j++){
i++;
if(word.charAt(j) != scentence.charAt(i)){
break;
}
else{
count++;
}
}
if(count == word.length()){
wordCount++;
}
}
}
System.out.println("The word "+ word + " was repeated :" + wordCount);
}
}
In order to remove all subviews from superviews:
NSArray *oSubView = [self subviews];
for(int iCount = 0; iCount < [oSubView count]; iCount++)
{
id object = [oSubView objectAtIndex:iCount];
[object removeFromSuperview];
iCount--;
}
I know this is an old one with an accepted answer, and that answer works great.. IF you are not styling the background and floating the final inputs left. If you are, then the form background will not include the floated input fields.
To avoid this make the divs with the smaller input fields inline-block rather than float left.
This:
<div style="display:inline-block;margin-right:20px;">
<label for="name">Name</label>
<input id="name" type="text" value="" name="name">
</div>
Rather than:
<div style="float:left;margin-right:20px;">
<label for="name">Name</label>
<input id="name" type="text" value="" name="name">
</div>
Or try defining the array as an object. (var cars = {};) Then there is no need to convert to json. This might not be practical in your example but worked well for me.
Agree it is probably due to a problem in resources that is preventing build of R.Java in gen. In my case a cut n paste had given a duplicate app name in string. Sort the fault, delete gen directory and clean.
In my case it was solved just passing proxy to connection. Thanks to @Andreas Panagiotidis.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<YOUR.HOST>", 80)));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy);
More detailed answer to help the newbies of VueJS:
And the code itself:
<script src="https://unpkg.com/vue-router"></script>
var router = new VueRouter({
mode: 'history',
routes: []
});
var vm = new Vue({
router,
el: '#app',
mounted: function() {
q = this.$route.query.q
console.log(q)
},
});
Here are functions you can use for creating and retrieving cookies.
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
I had a similar problem and found that if you remove the size definition, it works for some reason.
Remove:
<size
android:width="60dp"
android:height="40dp" />
from the shape.
Let me know if this works!
Open https://www.google-analytics.com/analytics.js file in a new tab, copy all the code.
Now create a folder in your web directory, rename it to google-analytics.
Create a text file in the same folder and paste all the code you copied above.
Rename the file ga-local.js
Now change the URL to call your locally hosted Analytics Script file in your Google Analytics Code. It will look something like this i.e. https://domain.xyz/google-analytics/ga.js
Finally, place your NEW google analytics code into the footer of your webpage.
You are good to go. Now check your website of Google PageSpeed Insights. It will not show the warning for Leverage Browser Caching Google Analytics. And the only problem with this solution is, to regularly update the Analytics Script manually.
BEST SOLUTION IS:
// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
// ...
// restore index and position
mList.post(new Runnable() {
@Override
public void run() {
mList.setSelectionFromTop(index, top);
}
});
YOU MUST CALL IN POST AND IN THREAD!
Yes, I believe you are creating thousands of objects. If you're looking for an easy way to delete a bunch of them at once, use canvas tags described here. This lets you perform the same operation (such as deletion) on a large number of objects.
Iterables are nicer:
const matches = (text, pattern) => ({
[Symbol.iterator]: function * () {
const clone = new RegExp(pattern.source, pattern.flags);
let match = null;
do {
match = clone.exec(text);
if (match) {
yield match;
}
} while (match);
}
});
Usage in a loop:
for (const match of matches('abcdefabcdef', /ab/g)) {
console.log(match);
}
Or if you want an array:
[ ...matches('abcdefabcdef', /ab/g) ]
this is a simple implementation:
lv.setOnScrollListener(new OnScrollListener() {
private int mLastFirstVisibleItem;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(mLastFirstVisibleItem<firstVisibleItem)
{
Log.i("SCROLLING DOWN","TRUE");
}
if(mLastFirstVisibleItem>firstVisibleItem)
{
Log.i("SCROLLING UP","TRUE");
}
mLastFirstVisibleItem=firstVisibleItem;
}
});
and if you need more precision, you can use this custom ListView class:
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
/**
* Created by root on 26/05/15.
*/
public class ScrollInterfacedListView extends ListView {
private OnScrollListener onScrollListener;
private OnDetectScrollListener onDetectScrollListener;
public ScrollInterfacedListView(Context context) {
super(context);
onCreate(context, null, null);
}
public ScrollInterfacedListView(Context context, AttributeSet attrs) {
super(context, attrs);
onCreate(context, attrs, null);
}
public ScrollInterfacedListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
onCreate(context, attrs, defStyle);
}
@SuppressWarnings("UnusedParameters")
private void onCreate(Context context, AttributeSet attrs, Integer defStyle) {
setListeners();
}
private void setListeners() {
super.setOnScrollListener(new OnScrollListener() {
private int oldTop;
private int oldFirstVisibleItem;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (onScrollListener != null) {
onScrollListener.onScrollStateChanged(view, scrollState);
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (onScrollListener != null) {
onScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
if (onDetectScrollListener != null) {
onDetectedListScroll(view, firstVisibleItem);
}
}
private void onDetectedListScroll(AbsListView absListView, int firstVisibleItem) {
View view = absListView.getChildAt(0);
int top = (view == null) ? 0 : view.getTop();
if (firstVisibleItem == oldFirstVisibleItem) {
if (top > oldTop) {
onDetectScrollListener.onUpScrolling();
} else if (top < oldTop) {
onDetectScrollListener.onDownScrolling();
}
} else {
if (firstVisibleItem < oldFirstVisibleItem) {
onDetectScrollListener.onUpScrolling();
} else {
onDetectScrollListener.onDownScrolling();
}
}
oldTop = top;
oldFirstVisibleItem = firstVisibleItem;
}
});
}
@Override
public void setOnScrollListener(OnScrollListener onScrollListener) {
this.onScrollListener = onScrollListener;
}
public void setOnDetectScrollListener(OnDetectScrollListener onDetectScrollListener) {
this.onDetectScrollListener = onDetectScrollListener;
}
public interface OnDetectScrollListener {
void onUpScrolling();
void onDownScrolling();
}
}
an example for use: (don't forget to add it as an Xml Tag in your layout.xml)
scrollInterfacedListView.setOnDetectScrollListener(new ScrollInterfacedListView.OnDetectScrollListener() {
@Override
public void onUpScrolling() {
//Do your thing
}
@Override
public void onDownScrolling() {
//Do your thing
}
});
In SQL Server Management Studio, go to Object Explorer > (your server) > Security > Logins
and right-click New Login
:
Then in the dialog box that pops up, pick the types of objects you want to see (Groups
is disabled by default - check it!) and pick the location where you want to look for your objects (e.g. use Entire Directory
) and then find your AD group.
You now have a regular SQL Server Login - just like when you create one for a single AD user. Give that new login the permissions on the databases it needs, and off you go!
Any member of that AD group can now login to SQL Server and use your database.
Just use the formula
120 = (HOUR(A8)*3600+MINUTE(A8)*60+SECOND(A8))/60
For port 80, the command would be : netstat -an | find "80" For port n, the command would be : netstat -an | find "n"
Here, netstat is the instruction to your machine
-a : Displays all connections and listening ports -n : Displays all address and instructions in numerical format (This is required because output from -a can contain machine names)
Then, a find command to "Pattern Match" the output of previous command.
Try to use r.hasNext() instead of r.hasNextLine():
while(r.hasNext()) {
scan = r.next();
protected void DrugGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
// To check condition on integer value
if (Convert.ToInt16(DataBinder.Eval(e.Row.DataItem, "Dosage")) == 50)
{
e.Row.BackColor = System.Drawing.Color.Cyan;
}
}
Abstract classes are not required to implement the methods. So even though it implements an interface, the abstract methods of the interface can remain abstract. If you try to implement an interface in a concrete class (i.e. not abstract) and you do not implement the abstract methods the compiler will tell you: Either implement the abstract methods or declare the class as abstract.
All third=party tools mentioned below are 100% free.
I’ve used ApexSQL Search with good success for searching both objects and data in tables. It comes with several other features such as relationship diagrams and such…
I was a bit slow on large (40GB TFS Database) databases though…
Apart from this there is also SSMS Tools pack that offers a lot of other features that are quite useful even though these are not directly related to searching text.
To be able to use std::unordered_map
(or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:
A hash function; this must be a class that overrides operator()
and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash
template for your key-type.
A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator()
, or as a specialization of std::equal
, or – easiest of all – by overloading operator==()
for your key type (as you did already).
The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.
A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
With this in place, you can instantiate a std::unordered_map
for the key-type:
int main()
{
std::unordered_map<Key,std::string> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
It will automatically use std::hash<Key>
as defined above for the hash value calculations, and the operator==
defined as member function of Key
for equality checks.
If you don't want to specialize template inside the std
namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
int main()
{
std::unordered_map<Key,std::string,KeyHasher> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.
This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value
and hash_combine
function template from the Boost library. The former acts in a similar way as std::hash
for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:
#include <boost/functional/hash.hpp>
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using boost::hash_value;
using boost::hash_combine;
// Start with a hash value of 0 .
std::size_t seed = 0;
// Modify 'seed' by XORing and bit-shifting in
// one member of 'Key' after the other:
hash_combine(seed,hash_value(k.first));
hash_combine(seed,hash_value(k.second));
hash_combine(seed,hash_value(k.third));
// Return the result.
return seed;
}
};
And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:
namespace std
{
template <>
struct hash<Key>
{
size_t operator()( const Key& k ) const
{
// Compute individual hash values for first, second and third
// http://stackoverflow.com/a/1646913/126995
size_t res = 17;
res = res * 31 + hash<string>()( k.first );
res = res * 31 + hash<string>()( k.second );
res = res * 31 + hash<int>()( k.third );
return res;
}
};
}
hi if are you new in android use this way Apply your view to make it gone GONE is one way, else, get hold of the parent view, and remove the child from there..... else get the parent layout and use this method an remove all child parentView.remove(child)
I would suggest using the GONE approach...
Nested Depth for BSON Documents: MongoDB supports no more than 100 levels of nesting for BSON documents.
time = Time.zone.now()
It will work as
irb> Time.zone.now
=> 2017-12-02 12:06:41 UTC
Don't have enough reputation to comment yet. Using Ubuntu and a simple:
sudo apt-get install php5-curl
sudo /etc/init.d/apache2 restart
Did NOT work for me.
For some reason curl.so
was installed in a location not picked up by default. I checked the extension_dir
in my php.ini and copied over the curl.so
to my extension_dir
cp /usr/lib/php5/20090626/curl.so /usr/local/lib/php/extensions/no-debug-non-zts-20090626
Hope this helps someone, adjust your path locations accordingly.
One important function of the main
key is that it provides the path for your entry point. This is very helpful when working with nodemon
. If you work with nodemon
and you define the main
key in your package.json
as let say "main": "./src/server/app.js"
, then you can simply crank up the server with typing nodemon
in the CLI with root as pwd instead of nodemon ./src/server/app.js
.
Using jQuery's .is( ":focus" )
$(".status").on("click","textarea",function(){
if ($(this).is( ":focus" )) {
// fire this step
}else{
$(this).focus();
// fire this step
}
If it were me doing it I'd use sed:
sed -e '$s/$/\n/' -s *.txt > finalfile.txt
In this sed pattern $ has two meanings, firstly it matches the last line number only (as a range of lines to apply a pattern on) and secondly it matches the end of the line in the substitution pattern.
If your version of sed doesn't have -s
(process input files separately) you can do it all as a loop though:
for f in *.txt ; do sed -e '$s/$/\n/' $f ; done > finalfile.txt
BEWARE:
enum Example
{
One = 1,
Two = 2,
Three = 3
}
Enum.(Try)Parse()
accepts multiple, comma-separated arguments, and combines them with binary 'or' |
. You cannot disable this and in my opinion you almost never want it.
var x = Enum.Parse("One,Two"); // x is now Three
Even if Three
was not defined, x
would still get int value 3
. That's even worse: Enum.Parse() can give you a value that is not even defined for the enum!
I would not want to experience the consequences of users, willingly or unwillingly, triggering this behavior.
Additionally, as mentioned by others, performance is less than ideal for large enums, namely linear in the number of possible values.
I suggest the following:
public static bool TryParse<T>(string value, out T result)
where T : struct
{
var cacheKey = "Enum_" + typeof(T).FullName;
// [Use MemoryCache to retrieve or create&store a dictionary for this enum, permanently or temporarily.
// [Implementation off-topic.]
var enumDictionary = CacheHelper.GetCacheItem(cacheKey, CreateEnumDictionary<T>, EnumCacheExpiration);
return enumDictionary.TryGetValue(value.Trim(), out result);
}
private static Dictionary<string, T> CreateEnumDictionary<T>()
{
return Enum.GetValues(typeof(T))
.Cast<T>()
.ToDictionary(value => value.ToString(), value => value, StringComparer.OrdinalIgnoreCase);
}
This approach is very right: Destruct any specific state "NAME" to ignore and keep others.
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state.NAME = undefined
}
return appReducer(state, action)
}
I found this to be weird but I got a solution. I noticed that every once in a while my project folder went read-only and I couldn't save it from VS. So I read a suggestion to transfer NPM from local user PATH to system-wide PATH global variable, and it worked like a charm.
this one is working for me also for internet explorer:
<div class="col imagebox" [ngStyle]="bkUrl"></div>
...
@Input() background = '571x450img';
bkUrl = {};
ngOnInit() {
this.bkUrl = this.getBkUrl();
}
getBkUrl() {
const styles = {
'background-image': 'url(src/assets/images/' + this.background + '.jpg)'
};
console.log(styles);
return styles;
}
char originalString[] = "THESTRINGHASNOSPACES";
char aux[5];
int j=0;
for(int i=0;i<strlen(originalString);i++){
aux[j] = originalString[i];
if(j==3){
aux[j+1]='\0';
printf("%s\n",aux);
j=0;
}else{
j++;
}
}
My current work machine came with bitlocker, and being an upgrade from the prior model. It only seemed faster to me. What I have found, however, is that bitlocker is more bullet proof than truecrypt, when it comes to accurately laying down the data. I do a lot of work in SAS which constantly writes backup copies to disk as it moves along and shoots a variety of output types to disk at the end. SAS works fine writing output from multithreaded processes back to bitlocker and doesn't seem to know it's there. This has not been the case for me with truecrypt. I'm not sure what happens or how, but I found that processes got out of synch when working with source/output data in a truecrypt container, which is what I installed on my second work computer since it had no bitlocker. The constant backups were shooting to an SSD while the truecrypt results were on a regular HD. Maybe that speed difference helped trip it up. Whatever the cause, I had to quit using truecrypt on that second computer because it made my SAS results out of synch with respect to processing order and it screwed up some of my processes and data. Scary stuff in my world.
I work with people who have successfully used Truecrypt on the exact same computer, but they weren't using a disk intensive app. like SAS.
Bitlocker to Go, the encryption which bitlocker applies to thumb-drives, does slow things down quite a bit when it comes to read/write times. It's not too hard to use as long as you remember your password on the thumbdrive, and are willing to wait for it to format/initialize the drive, but in my experience it made access to the flash drive about 4 times as slow. Don't know why it would slow down a thumb drive and not a disk but that's how it was for me and my coworker.
Based on my success with bitlocker at work, I bought Windows Pro for my home computer to get bitlocker and plan to encrypt some directories with it for things like financials.
The accepted answers really limit what you can do with your code. For example, you would not be able to search an array of Object Ids
by using the equals method. Instead, it would make more sense to always cast to string and compare the keys.
Here's an example answer in case if you need to use indexOf()
to check within an array of references for a specific id. assume query
is a query you are executing, assume someModel
is a mongo model for the id you are looking for, and finally assume results.idList
is the field you are looking for your object id in.
query.exec(function(err,results){
var array = results.idList.map(function(v){ return v.toString(); });
var exists = array.indexOf(someModel._id.toString()) >= 0;
console.log(exists);
});
use the builtin: (no need for tkinter)
s = input('->>')
print(s) # what you just typed); now use if's
If you by any chance using java for configuration, you may need to check the below bean
declaration if you have package level changes. Eg: com.abc.spring
package changed to com.bbc.spring
@Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
//builder.scanPackages("com.abc.spring"); //Comment this line as this package no longer valid.
builder.scanPackages("com.bbc.spring");
builder.addProperties(getHibernationProperties());
return builder.buildSessionFactory();
}
The original request has been answered already.
However, I am posting the below answer for those who might be looking for generic transliteration code to transliterate any charset to Latin/English in Java.
Naive meaning of tranliteration: Translated string in it's final form/target charset sounds like the string in it's original form. If we want to transliterate any charset to Latin(English alphabets), then ICU4(ICU4J library in java ) will do the job.
Here is the code snippet in java:
import com.ibm.icu.text.Transliterator; //ICU4J library import
public static String TRANSLITERATE_ID = "NFD; Any-Latin; NFC";
public static String NORMALIZE_ID = "NFD; [:Nonspacing Mark:] Remove; NFC";
/**
* Returns the transliterated string to convert any charset to latin.
*/
public static String transliterate(String input) {
Transliterator transliterator = Transliterator.getInstance(TRANSLITERATE_ID + "; " + NORMALIZE_ID);
String result = transliterator.transliterate(input);
return result;
}
Add your C:\WinPython-64bit-3.4.4.1\python_***\Scripts folder to your system PATH variable by doing the following:
Click Environment Variables. ...
In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. ...
I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.
Vendor bundle.
You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor
), and file name that will be generated (vendor.js
).
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),
Now important part, you have to now specify what does it mean vendor
library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor
bundle.
in your case it should look something like:
entry: {
app: 'entry.js',
vendor: ['jquery', 'jquery.plugin1']
}
JQuery as global
Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:
new webpack.ProvidePlugin({
$: "jquery"
})
And now you can just use $
anywhere in your code - webpack will automatically convert that to
require('jquery')
I hope it helped. you can also look at my webpack configuration file that is here
I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)
Edit:
To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:
new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),
and then declare different extenral libraries for different files:
entry: {
page1: ['entry.js'],
page2: ['entry2.js'],
"vendor-page1": [
'lodash'
],
"vendor-page2": [
'jquery'
]
},
If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.
Have a look at the official issue 33930. There is pointed out, that it may have to do with the start up of OpenGL during the start of the emulator. Others wrote it only crashes when they use WXGA800-skin and suggest to manually set the resolution to 800x1280.
Further there are ZIP-files provided to manually downgrade your android SDK to version 19 and plattform-tools to version 11. This may help as well to temporally fix the issue.
Tuesday, December 3, 2019
https://androidstudio.googleblog.com/2019/12/emulator-29211-and-amd-hypervisor-12-to.html
Via AMD Hypervisor, we added support for running the emulator on AMD CPUs on Windows:
Here's what worked for me:
git diff origin/master...
This shows only the changes between my currently selected local branch and the remote master branch, and ignores all changes in my local branch that came from merge commits.
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
Made it.
from datetime import datetime
dateNow = datetime.now().strftime('%Y%m%d')
You can do it without having to keep track of the previous scroll top, as all the other examples require:
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
console.log('Scroll up');
}
else {
console.log('Scroll down');
}
});
I am not an expert on this so feel free to research it further, but it appears that when you use $(element).scroll
, the event being listened for is a 'scroll' event.
But if you specifically listen for a mousewheel
event by using bind, the originalEvent
attribute of the event parameter to your callback contains different information. Part of that information is wheelDelta
. If it's positive, you moved the mousewheel up. If it's negative, you moved the mousewheel down.
My guess is that mousewheel
events will fire when the mouse wheel turns, even if the page does not scroll; a case in which 'scroll' events probably are not fired. If you want, you can call event.preventDefault()
at the bottom of your callback to prevent the page from scrolling, and so that you can use the mousewheel event for something other than a page scroll, like some type of zoom functionality.
Last revision merged from trunk to branch can be found by running this command inside the working copy directory:
svn log -v --stop-on-copy
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
If none of the above works then try and go this question and answer: Maven error "Failure to transfer..."
and delete your .lastUpdated
files.
I did an upgraded version of jezzipin's answer (and I'm animating padding top instead of height but you still get the point.
/**
* ResizeHeaderOnScroll
*
* @constructor
*/
var ResizeHeaderOnScroll = function()
{
this.protocol = window.location.protocol;
this.domain = window.location.host;
};
ResizeHeaderOnScroll.prototype.init = function()
{
if($(document).scrollTop() > 0)
{
$('header').data('size','big');
} else {
$('header').data('size','small');
}
ResizeHeaderOnScroll.prototype.checkScrolling();
$(window).scroll(function(){
ResizeHeaderOnScroll.prototype.checkScrolling();
});
};
ResizeHeaderOnScroll.prototype.checkScrolling = function()
{
if($(document).scrollTop() > 0)
{
if($('header').data('size') == 'big')
{
$('header').data('size','small');
$('header').stop().animate({
paddingTop:'1em',
paddingBottom:'1em'
},200);
}
}
else
{
if($('header').data('size') == 'small')
{
$('header').data('size','big');
$('header').stop().animate({
paddingTop:'3em'
},200);
}
}
}
$(document).ready(function(){
var resizeHeaderOnScroll = new ResizeHeaderOnScroll();
resizeHeaderOnScroll.init()
})
I will try to give the solution that worked for me. It seems that different set of problems can lead to this situation.
32 bit software works in 64 bit OS. I installed anaconda-3 (32 bit) in my 64 bit OS. It was working perfectly fine. I decided to install tensorflow in my machine and it wouldn't install at first. I was using conda environment to install tensorflow and got this error.
Solution is if you are running 64 bit OS, install 64 bit anaconda and if 32 bit OS then 32 bit anaconda. Then follow the standard procedure mentioned in tensorflow website for windows (anaconda installation). This made it possible to install tensorflow without any problem.
Create a C# class that maps to your Json and use Newsoft JsonConvert
to Deserialise it.
For example:
public Class MyResponse
{
public Meta Meta { get; set; }
public Response Response { get; set; }
}
If you have just upgraded to SVN 1.7 on your machine (like I just did), and have a lot of projects in your Eclipse workspace which need to be upgraded, you can do the following in a terminal window on Unix-baesd systems:
cd [eclipse/workspace] # <- you supply the actual path here
for file in `find . -depth 2 -name "*.svn"`; do svn upgrade `dirname $file` ; done;
After Googling a bit, I found what seems to be the equivalent for Windows users:
http://www.rqna.net/qna/mnrmqn-how-to-find-all-svn-working-copies-on-win-xp.html
See the answer by Alexey Shcherbak halfway down the page.
jQuery(".megamenu li.level0 .dropdown-container .sub-column ul .level1").on("mouseover", function () {
var sum = 0;
jQuery(this).find('ul li.level2').each(function(){
sum -= jQuery(this).height();
jQuery(this).parent('ul').css('margin-top', sum / 1.8);
console.log(sum);
});
});
On hover we can calculate the list item height.
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(Calendar.getInstance().getTime());
Assuming ASCII strings:
string1 = 'Hello'
string2 = 'hello'
if string1.lower() == string2.lower():
print("The strings are the same (case insensitive)")
else:
print("The strings are NOT the same (case insensitive)")
Try to use this:
using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
{
//add parameters on request
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("test", "test"),
new KeyValuePair<string, string>("test1", "test1")
};
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
//client.DefaultRequestHeaders.Add("Accept", "*/*");
client.Timeout = TimeSpan.FromMilliseconds(10000);
var res = await client.PostAsync("", new FormUrlEncodedContent(body));
if (res.IsSuccessStatusCode)
{
var exec = await res.Content.ReadAsStringAsync();
Console.WriteLine(exec);
}
}
}
I was able to use nginx to handle the 301 redirect to the aws signin page.
Go to your nginx conf folder (in my case it's /etc/nginx/sites-available
in which I create a symlink to /etc/nginx/sites-enabled
for the enabled conf files).
Then add a redirect path
server {
listen 80;
server_name aws.example.com;
return 301 https://myaccount.signin.aws.amazon.com/console;
}
If you are using nginx, you will most likely have additional server blocks (virtualhosts in apache terminology) to handle your zone apex (example.com) or however you have it setup. Make sure that you have one of them set to be your default server.
server {
listen 80 default_server;
server_name example.com;
# rest of config ...
}
In Route 53, add an A record
for aws.example.com
and set the value to the same IP used for your zone apex.
Pretty much everybody is using getopt
Here is the example code for the doc :
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError:
# print help information and exit:
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-o", "--output"):
output = a
So in a word, here is how it works.
You've got two types of options. Those who are receiving arguments, and those who are just like switches.
sys.argv
is pretty much your char** argv
in C. Like in C you skip the first element which is the name of your program and parse only the arguments : sys.argv[1:]
Getopt.getopt
will parse it according to the rule you give in argument.
"ho:v"
here describes the short arguments : -ONELETTER
. The :
means that -o
accepts one argument.
Finally ["help", "output="]
describes long arguments ( --MORETHANONELETTER
).
The =
after output once again means that output accepts one arguments.
The result is a list of couple (option,argument)
If an option doesn't accept any argument (like --help
here) the arg
part is an empty string.
You then usually want to loop on this list and test the option name as in the example.
I hope this helped you.
Adding the following $cfg helps to narrow down the problem
$cfg['Error_Handler']['display'] = true;
$cfg['Error_Handler']['gather'] = true;
Don't forget to remove those $cfg after done debugging!
Here is ES6 version of using arrow function in filter. Posting this as an answer because most of us are using ES6 these days and may help readers to do filter in advanced way using arrow function, let and const.
const filter = {_x000D_
address: 'England',_x000D_
name: 'Mark'_x000D_
};_x000D_
let users = [{_x000D_
name: 'John',_x000D_
email: '[email protected]',_x000D_
age: 25,_x000D_
address: 'USA'_x000D_
},_x000D_
{_x000D_
name: 'Tom',_x000D_
email: '[email protected]',_x000D_
age: 35,_x000D_
address: 'England'_x000D_
},_x000D_
{_x000D_
name: 'Mark',_x000D_
email: '[email protected]',_x000D_
age: 28,_x000D_
address: 'England'_x000D_
}_x000D_
];_x000D_
_x000D_
_x000D_
users= users.filter(item => {_x000D_
for (let key in filter) {_x000D_
if (item[key] === undefined || item[key] != filter[key])_x000D_
return false;_x000D_
}_x000D_
return true;_x000D_
});_x000D_
_x000D_
console.log(users)
_x000D_
You just need to add this line to the window there:
exec (your stored proc name) (and possibly add parameters)
What is your stored proc called, and what parameters does it expect?
Beware of triggers. Maybe the issue is with some operation in the trigger for inserted rows.
Just as others stated you need to remove the ';
' from:
;extension=php_mysql.dll
and
;extension=php_mysqli.dll
in your php.ini to enable mysql and mysqli extensions. But MOST IMPORTANT of all, you should set the extension_dir
in your php.ini to point to your extensions directory. The default most of the time is "ext
". You should change it to the absolute path to the extensions folder. i.e. if you have your xampp installed on drive C, then C:/xampp/php/ext
is the absolute path to the ext folder, and It should work like a charm!
Surprised no one mentioned flask.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: http://vimeo.com/18399381 and here vimeo . com / 18232653
This is an easy and fast way to export a table to a script with pgAdmin manually without extra installations:
This method also works with the technique of making an export_table as demonstrated in @Clodoaldo Neto's answer.
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
subjob.Items.Add(dr[i]);
}
}
to read rows in one colunmn
Here is my solution:
SELECT
DISTINCT NAME,
MAX(MESSAGES) OVER(PARTITION BY NAME) MESSAGES
FROM MESSAGE;
I usually use a dictionary, not a list to return JSON content.
import json
from django.http import HttpResponse
response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'
Pre-Django 1.7 you'd return it like this:
return HttpResponse(json.dumps(response_data), content_type="application/json")
For Django 1.7+, use JsonResponse
as shown in this SO answer like so :
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
If you want to control the level of transparency you can use rgba. where a is the alpha. 0 for transparent and 1 for opaque. Make sure that final output file must have .png extension for transparency.
convert
test.png
-channel rgba
-matte
-fuzz 40%
-fill "rgba(255,255,255,0.5)"
-opaque "rgb(255,255,255)"
semi_transparent.png
The original question addresses a specific narrow use case. For those who need more generic answers here are some examples:
Given the dataframe below:
import pandas as pd
import numpy as np
df = pd.DataFrame([['dog', 'hound', 5],
['cat', 'ragdoll', 1]],
columns=['animal', 'type', 'age'])
In[1]:
Out[1]:
animal type age
----------------------
0 dog hound 5
1 cat ragdoll 1
Below we are adding a new description
column as a concatenation of other columns by using the +
operation which is overridden for series. Fancy string formatting, f-strings etc won't work here since the +
applies to scalars and not 'primitive' values:
df['description'] = 'A ' + df.age.astype(str) + ' years old ' \
+ df.type + ' ' + df.animal
In [2]: df
Out[2]:
animal type age description
-------------------------------------------------
0 dog hound 5 A 5 years old hound dog
1 cat ragdoll 1 A 1 years old ragdoll cat
We get 1 years
for the cat (instead of 1 year
) which we will be fixing below using conditionals.
Here we are replacing the original animal
column with values from other columns, and using np.where
to set a conditional substring based on the value of age
:
# append 's' to 'age' if it's greater than 1
df.animal = df.animal + ", " + df.type + ", " + \
df.age.astype(str) + " year" + np.where(df.age > 1, 's', '')
In [3]: df
Out[3]:
animal type age
-------------------------------------
0 dog, hound, 5 years hound 5
1 cat, ragdoll, 1 year ragdoll 1
A more flexible approach is to call .apply()
on an entire dataframe rather than on a single column:
def transform_row(r):
r.animal = 'wild ' + r.type
r.type = r.animal + ' creature'
r.age = "{} year{}".format(r.age, r.age > 1 and 's' or '')
return r
df.apply(transform_row, axis=1)
In[4]:
Out[4]:
animal type age
----------------------------------------
0 wild hound dog creature 5 years
1 wild ragdoll cat creature 1 year
In the code above the transform_row(r)
function takes a Series
object representing a given row (indicated by axis=1
, the default value of axis=0
will provide a Series
object for each column). This simplifies processing since we can access the actual 'primitive' values in the row using the column names and have visibility of other cells in the given row/column.
SELECT
[DATABASE] = DB_NAME(DBID),
OPNEDCONNECTIONS =COUNT(DBID),
[USER] =LOGINAME
FROM SYS.SYSPROCESSES
GROUP BY DBID, LOGINAME
ORDER BY DB_NAME(DBID), LOGINAME