There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
If the link is to a valid file url, simply assigning window.location.href will work.
However, sometimes the link is not valid, and an iFrame is required.
Do your normal event.preventDefault to prevent the window from opening, and if you are using jQuery, this will work:
$('<iframe>').attr('src', downloadThing.attr('href')).appendTo('body').on("load", function() {
$(this).remove();
});
my solution:
; (function ($) {
$.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = $.fn[ name ];
$.fn[ name ] = function( speed, easing, callback ) {
if(speed == null || typeof speed === "boolean"){
var ret=cssFn.apply( this, arguments )
$.fn.triggerVisibleEvent.apply(this,arguments)
return ret
}else{
var that=this
var new_callback=function(){
callback.call(this)
$.fn.triggerVisibleEvent.apply(that,arguments)
}
var ret=this.animate( genFx( name, true ), speed, easing, new_callback )
return ret
}
};
});
$.fn.triggerVisibleEvent=function(){
this.each(function(){
if($(this).is(':visible')){
$(this).trigger('visible')
$(this).find('[data-trigger-visible-event]').triggerVisibleEvent()
}
})
}
})(jQuery);
for example:
if(!$info_center.is(':visible')){
$info_center.attr('data-trigger-visible-event','true').one('visible',processMoreLessButton)
}else{
processMoreLessButton()
}
function processMoreLessButton(){
//some logic
}
It stops and starts the services that IIS consists of.
You can think of it as closing the relevant program and starting it up again.
I had this same issue before and found this snippet very useful:
class Tee(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
from: http://mail.python.org/pipermail/python-list/2007-May/438106.html
I just wanted to include a link to a resolution to an issue I was having with VS2008 and TFS08.
I accidently opened my solution without being connected to my network and was not able to get it "back the way it was" and had to rebind every time I openned.
I found the solution here; http://www.fkollmann.de/v2/post/Visual-Studio-2008-refuses-to-bind-to-TFS-or-to-open-solution-source-controlled.aspx
Basically, you need to open the "Connect to Team Foundation Server" and then "Servers..." once there, Delete/Remove your server and re-add it. This fixed my issue.
xhr.getResponseHeader('Set-Cookie');
It won't work for me.
I use this
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
success: function(output, status, xhr) {
alert(getCookie("MyCookie"));
},
The solution I found was to use the New-Object cmdlet to initialize an array of the proper size.
$array = new-object object[] 5
for($i=0; $i -lt $array.Length;$i++)
{
$array[$i] = $FALSE
}
using System;
using System.IO;
public class GetwithoutExtension
{
public static void Main()
{
//D:Dir dhould exists in ur system
DirectoryInfo dir1 = new DirectoryInfo(@"D:Dir");
FileInfo [] files = dir1.GetFiles("*xls", SearchOption.AllDirectories);
foreach (FileInfo f in files)
{
string filename = f.Name.ToString();
filename= filename.Replace(".xls", "");
Console.WriteLine(filename);
}
Console.ReadKey();
}
}
CORS is a browser feature. Servers need to opt into CORS to allow browsers to bypass same-origin policy. Your server would not have that same restriction and be able to make requests to any server with a public API. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Create an endpoint on your server with CORS enabled that can act as a proxy for your web app.
Programs return a 16 bit exit code. If the program was killed with a signal then the high order byte contains the signal used, otherwise the low order byte is the exit status returned by the programmer.
How that exit code is assigned to the status variable $? is then up to the shell. Bash keeps the lower 7 bits of the status and then uses 128 + (signal nr) for indicating a signal.
The only "standard" convention for programs is 0 for success, non-zero for error. Another convention used is to return errno on error.
Try Dijkstra's algorithm on the following graph, assuming A
is the source node and D
is the destination, to see what is happening:
Note that you have to follow strictly the algorithm definition and you should not follow your intuition (which tells you the upper path is shorter).
The main insight here is that the algorithm only looks at all directly connected edges and it takes the smallest of these edge. The algorithm does not look ahead. You can modify this behavior , but then it is not the Dijkstra algorithm anymore.
I too faced the same issue. I followed the following steps to resolve my issue -
If the above steps don't work for you, instead of Workspace default JRE, you can choose an Alternate JRE and give the path to the JRE that you want to point.
I know this question is about visual studio 2015. I faced this issue with visual studio 2017. When searched on google I landed to this page. After looking at first 2,3 answers I realized this is the problem with vc++ installation. Installing the workload "Desktop development with c++" resolved the issue.
Sounds like you really want a Dictionary<int, string>
or possibly a switch
statement...
You can do it with the conditional operator though:
userType = user.Type == 0 ? "Admin"
: user.Type == 1 ? "User"
: user.Type == 2 ? "Employee"
: "The default you didn't specify";
While you could put that in one line, I'd strongly urge you not to.
I would normally only do this for different conditions though - not just several different possible values, which is better handled in a map.
It is lot easier to understand an idea through example. What have been told about callback function in C so far are great answers, but probably the biggest benefit of using the feature is to keep the code clean and uncluttered.
The following C code implements quick sorting. The most interesting line in the code below is this one, where we can see the callback function in action:
qsort(arr,N,sizeof(int),compare_s2b);
The compare_s2b is the name of function which qsort() is using to call the function. This keeps qsort() so uncluttered (hence easier to maintain). You just call a function by name from inside another function (of course, the function prototype declaration, at the least, must precde before it can be called from another function).
#include <stdio.h>
#include <stdlib.h>
int arr[]={56,90,45,1234,12,3,7,18};
//function prototype declaration
int compare_s2b(const void *a,const void *b);
int compare_b2s(const void *a,const void *b);
//arranges the array number from the smallest to the biggest
int compare_s2b(const void* a, const void* b)
{
const int* p=(const int*)a;
const int* q=(const int*)b;
return *p-*q;
}
//arranges the array number from the biggest to the smallest
int compare_b2s(const void* a, const void* b)
{
const int* p=(const int*)a;
const int* q=(const int*)b;
return *q-*p;
}
int main()
{
printf("Before sorting\n\n");
int N=sizeof(arr)/sizeof(int);
for(int i=0;i<N;i++)
{
printf("%d\t",arr[i]);
}
printf("\n");
qsort(arr,N,sizeof(int),compare_s2b);
printf("\nSorted small to big\n\n");
for(int j=0;j<N;j++)
{
printf("%d\t",arr[j]);
}
qsort(arr,N,sizeof(int),compare_b2s);
printf("\nSorted big to small\n\n");
for(int j=0;j<N;j++)
{
printf("%d\t",arr[j]);
}
exit(0);
}
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
Behold HTML comments:
<!-- comment -->
http://www.w3.org/TR/html401/intro/sgmltut.html#idx-HTML
The proper way to delete code without deleting it, of course, is to use version control, which enables you to resurrect old code from the past. Don't get into the habit of accumulating commented-out code in your pages, it's no fun. :)
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
Use:
L = ['Thanks You', 'Its fine no problem', 'Are you sure']
#create new df
df = pd.DataFrame({'col':L})
print (df)
col
0 Thanks You
1 Its fine no problem
2 Are you sure
df = pd.DataFrame({'oldcol':[1,2,3]})
#add column to existing df
df['col'] = L
print (df)
oldcol col
0 1 Thanks You
1 2 Its fine no problem
2 3 Are you sure
Thank you DYZ:
#default column name 0
df = pd.DataFrame(L)
print (df)
0
0 Thanks You
1 Its fine no problem
2 Are you sure
Actually the current browsing path to the Chrome cookies in the address bar is: chrome://settings/content/cookies
Hey wrote a little mapper function that might help.
function propertyMapper(object, src){
for (var property in object) {
for (var sourceProp in src) {
if(property === sourceProp){
if(Object.prototype.toString.call( property ) === '[object Array]'){
propertyMapper(object[property], src[sourceProp]);
}else{
object[property] = src[sourceProp];
}
}
}
}
}
You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:
<div class="container">
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4">
<div class="centerBlock">
<img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
</div>
</div>
<div class="col-sm-8 col-md-8 col-lg-8">
Some content not important at this moment
</div>
</div>
</div>
// CSS
.centerBlock {
display: table;
margin: auto;
}
You can simply do the following :
$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));
Okay, it is a few days ago... In my current case, the answer from ZloiAdun does not work for me, but brings me very close to my solution...
Instead of:
element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
the following code makes me happy:
element.sendKeys(Keys.HOME, Keys.chord(Keys.SHIFT, Keys.END), "55");
So I hope that helps somebody!
This rule
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
is wrong. It says to create a file named producer.o (with -o producer.o
), but you want to create a file named main
. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o
As Shahbaz rightly points out, the gmake professionals would also use $^
which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ $^
For me, this error occurred in my django project because of the following:
I inserted a new hyperlink in my home.html present in templates folder of my project as below:
<input type="button" value="About" onclick="location.href='{% url 'about' %}'">
_x000D_
In views.py, I had the following definitions of count and about:
def count(request):
fulltext = request.GET['fulltext']
wordlist = fulltext.split()
worddict = {}
for word in wordlist:
if word in worddict:
worddict[word] += 1
else:
worddict[word] = 1
worddict = sorted(worddict.items(), key = operator.itemgetter(1),reverse=True)
return render(request,'count.html', 'fulltext':fulltext,'count':len(wordlist),'worddict'::worddict})
def about(request):
return render(request,"about.html")
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.homepage,name="home"),
path('eggs',views.eggs),
path('count/',views.count,name="count"),
path('about/',views.count,name="about"),
]
As can be seen in no. 3 above,in the last url pattern, I was incorrectly calling views.count whereas I needed to call views.about.
This line fulltext = request.GET['fulltext']
in count function (which was mistakenly called because of wrong entry in urlpatterns) of views.py threw the multivaluedictkeyerror exception.
Then I changed the last url pattern in urls.py to the correct one i.e. path('about/',views.about,name="about")
, and everything worked fine.
Apparently, in general a newbie programmer in django can make the mistake I made of wrongly calling another view function for a url, which might be expecting different set of parameters or passing different set of objects in its render call, rather than the intended behavior.
Hope this helps some newbie programmer to django.
Solution without charts
Function SelectionToPicture(nome)
'save location ( change if you want )
FName = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & nome & ".jpg"
'copy selection and get size
Selection.CopyPicture xlScreen, xlBitmap
w = Selection.Width
h = Selection.Height
With ThisWorkbook.ActiveSheet
.Activate
Dim chtObj As ChartObject
Set chtObj = .ChartObjects.Add(100, 30, 400, 250)
chtObj.Name = "TemporaryPictureChart"
'resize obj to picture size
chtObj.Width = w
chtObj.Height = h
ActiveSheet.ChartObjects("TemporaryPictureChart").Activate
ActiveChart.Paste
ActiveChart.Export FileName:=FName, FilterName:="jpg"
chtObj.Delete
End With
End Function
If you're developing on an XAMPP, then you'll need an SMTP service to send the email. Try using a MailGun account. It's free and easy to use.
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
Nope. Totally a wrong way of iterating through an array. sizeof(texts)
is not equal to the number of elements in the array!
The modern, C++11 ways would be to:
std::array
if you want an array whose size is known at compile-time; orstd::vector
if its size depends on runtimeThen use range-for when iterating.
#include <iostream>
#include <array>
int main() {
std::array<std::string, 3> texts = {"Apple", "Banana", "Orange"};
// ^ An array of 3 elements with the type std::string
for(const auto& text : texts) { // Range-for!
std::cout << text << std::endl;
}
}
You may ask, how is std::array
better than the ol' C array? The answer is that it has the additional safety and features of other standard library containers, mostly closely resembling std::vector
. Further, The answer is that it doesn't have the quirks of decaying to pointers and thus losing type information, which, once you lose the original array type, you can't use range-for or std::begin/end
on it.
Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com
line. In Perl, say, something like
my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;
say decode_base64($sanitized_str);
might be what you want. It produces
This is simple ASCII Base64 for StackOverflow exmaple.
In Excel 2016 at least, you can use INDIRECT with a full path reference; the entire reference (including sheet name) needs to be enclosed by '
characters.
So this should work for you:
= INDIRECT("'C:\data\[myExcelFile.xlsm]" & C13 & "'!$A$1")
Note the closing '
in the last string (ie '!$A$1
surrounded by ""
)
A CSS keyword value that resets a property's value to the default specified by the browser in its UA stylesheet, as if the webpage had not included any CSS. For example, display:revert
on a <div>
would result in display:block
.
overflow: revert;
I think this will work properly
I had this issue occurring with mailto:
and tel:
links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.
Adding target="_blank"
, as suggested by this discussion of the issue fixed the problem for me.
Heads up! This solution is CSS-only.
I recommend you take advantage of CSS3 to do that, by hidding the by-default input radio button with CSS3 rules:
.options input{
margin:0;padding:0;
-webkit-appearance:none;
-moz-appearance:none;
appearance:none;
}
I just make an example a few days ago.
Off the top of my head, the following are the only built-ins that are subscriptable:
string: "foobar"[3] == "b"
tuple: (1,2,3,4)[3] == 4
list: [1,2,3,4][3] == 4
dict: {"a":1, "b":2, "c":3}["c"] == 3
But mipadi's answer is correct - any class that implements __getitem__
is subscriptable
If you are not given a specific file and you need to extract IP address then we need to do it recursively. grep command -> Searches a text or file for matching a given string and displays the matched string .
grep -roE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
-r
We can search the entire directory tree i.e. the current directory and all levels of sub-directories. It denotes recursive searching.
-o
Print only the matching string
-E
Use extended regular expression
If we would not have used the second grep command after the pipe we would have got the IP address along with the path where it is present
This simple technique will allow the makefile to function normally when forcing is not desired. Create a new target called force at the end of your makefile. The force target will touch a file that your default target depends on. In the example below, I have added touch myprogram.cpp. I also added a recursive call to make. This will cause the default target to get made every time you type make force.
yourProgram: yourProgram.cpp
g++ -o yourProgram yourProgram.cpp
force:
touch yourProgram.cpp
make
You are missing an include :
#include <stdlib.h>
, so GCC creates an implicit declaration of atof
and atod
, leading to garbage values.
And the format specifier for double is %f
, not %d
(that is for integers).
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;
}
/* Output */
price: 12.110000, 12.110000
Add
"rnpm": {
"assets": [
"./assets/fonts/"
]
}
in package.json
then run react-native link
As Chris shows, Linq will work; just use Last() to get a reference to the last one in the enumerable, and as long as you aren't working with that reference then do your normal code, but if you ARE working with that reference then do your extra thing. Its downside is that it will always be O(N)-complexity.
You can instead use Count() (which is O(1) if the IEnumerable is also an ICollection; this is true for most of the common built-in IEnumerables), and hybrid your foreach with a counter:
var i=0;
var count = Model.Results.Count();
foreach (Item result in Model.Results)
{
if (++i == count) //this is the last item
}
Just throw any RuntimeException
from a method marked as @Transactional
.
By default all RuntimeException
s rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor()
and noRollbackFor()
annotation parameters:
@Transactional(rollbackFor=Exception.class)
This will rollback transaction after throwing any exception.
You can also get an empty object by parsing JSON:
$blankObject= json_decode('{}');
Laravel 5.6.*
Controller
if(true) {
$msg = [
'message' => 'Some Message!',
];
return redirect()->route('home')->with($msg);
} else {
$msg = [
'error' => 'Some error!',
];
return redirect()->route('welcome')->with($msg);
}
Blade Template
@if (Session::has('message'))
<div class="alert alert-success" role="alert">
{{Session::get('message')}}
</div>
@elseif (Session::has('error'))
<div class="alert alert-warning" role="alert">
{{Session::get('error')}}
</div>
@endif
Enyoj
The programmatically trigger to call the autocomplete.change event is via a namespaced trigger on the source select element.
$("#CompanyList").trigger("blur.autocomplete");
Within version 1.8 of jquery UI..
.bind( "blur.autocomplete", function( event ) {
if ( self.options.disabled ) {
return;
}
clearTimeout( self.searching );
// clicks on the menu (or a button to trigger a search) will cause a blur event
self.closing = setTimeout(function() {
self.close( event );
self._change( event );
}, 150 );
});
a[len(a):]
- This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)]
it will get you the beginning to whatever is len(a)
.
Works particularly great for Google Earth Studio images:
ffmpeg -framerate 24 -i Project%03d.png Project.mp4
Try adding this class
class="pager"
<p class="pager" style="line-height: 70px;">
<button type="submit" class="btn">Confirm</button>
</p>
I tried mine within a <div class=pager><button etc etc></div>
which worked well
See http://getbootstrap.com/components/ look under Pagination -> Pager
This looks like the correct bootstrap class to center this, text-align: center;
is meant for text not images and blocks etc.
run this command on your terminal(here -v11 is for version 11(java11))-:
/usr/libexec/java_home -v11
you will get the path on your terminal something like this -:
/Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk/Contents/Home
now you need to open your bash profile in any editor for eg VS Code
if you want to edit your bash_profile in vs code then run this command -:
code ~/.bash_profile
else run this command and then press i to insert the path. -:
open ~/.bash_profile
you will get your .bash_profile now you need to add the path so add this in .bash_profile (path which you get from 1st command)-:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk/Contents/Home
if you were using code editor then now go to terminal and run this command to save the changes -:
source ~/.bash_profile
else press esc then :wq to exit from bash_profile then go to terminal and run the command given above. process completed. now you can check using this command -:
echo $JAVA_HOME
you will get/Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk/Contents/Home
Actually 3 of the options mentioned by other work.
1.
soup_object= BeautifulSoup(markup,"html.parser") #Python HTML parser
pip install lxml
soup_object= BeautifulSoup(markup,'lxml') # C dependent parser
pip install html5lib
soup_object= BeautifulSoup(markup,'html5lib') # C dependent parser
Why do you think you will lose data? Simply go into Management Studio and change the data type. If the existing value can be converted to bool (bit), it will do that. In other words, if "1" maps to true and "0" maps to false in your original field, you'll be fine.
Try this:
BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));
Those pesky black dots you are referencing to are called bullets.
They are pretty simple to remove, just add this line to your css:
ul {
list-style-type: none;
}
Hope this helps
Concerning the (somewhat off topic I know but since it was brought up earlier) XNA vs OpenGL choice, it might be beneficial in several cases to go with OpenGL instead of XNA (and in other XNA instead of OpenGL...).
If you are going to run the applications on Linux or Mac using Mono, it might be a good choice to go with OpenGL. Also, which isn't so widely known I think, if you have customers that are going to run your applications in a Citrix environment, then DirectX/Direct3D/XNA won't be as economical a choice as OpenGL. The reason for this is that OpenGL applications can be co-hosted on a lesser number of servers (due to performance issues a single server cannot host an infinite number of application instances) than DirectX/XNA applications which demands dedicated virtual servers to run in hardware accelerated mode. Other requirements exists like supported graphics cards etc but I will keep to the XNA vs OpenGL issue. As an IT Architect, Software developer etc this will have to be considered before choosing between OpenGL and DirectX/XNA...
A side note is that WebGL is based on OpenGL ES3 afaik...
As a further note, these are not the only considerations, but they might make the choice easier for some...
A condensed code block is as follows:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// things to do on the main thread
}
});
This does not involve passing down the Activity reference or the Application reference.
Kotlin Equivalent:
Handler(Looper.getMainLooper()).post(Runnable {
// things to do on the main thread
})
Also In VS 2015 Community Edition
go to Debug->Options or Tools->Options
and check Debugging->General->Suppress JIT optimization on module load (Managed only)
OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom"
instead of app:showAsAction="ifRoom"
since i am using v7 library.
However the title is coming at center of extended toolbar. How to make it appear at the top?
Had one of these as well, but the parameter of the action was an interface with no public properties. Ended up using It.Is() with a seperate method and within this method had to do some mocking of the interface
public interface IQuery
{
IQuery SetSomeFields(string info);
}
void DoSomeQuerying(Action<IQuery> queryThing);
mockedObject.Setup(m => m.DoSomeQuerying(It.Is<Action<IQuery>>(q => MyCheckingMethod(q)));
private bool MyCheckingMethod(Action<IQuery> queryAction)
{
var mockQuery = new Mock<IQuery>();
mockQuery.Setup(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition())
queryAction.Invoke(mockQuery.Object);
mockQuery.Verify(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition(), Times.Once)
return true
}
Instead of using valueOf(long)
and parse()
, you can directly use the BigInteger constructor that takes a string argument:
BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");
That should give you the desired value.
Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.
Here are the commands to retrieve key value:
<key>
<key>
<key> <start> <end>
<key>
<key> <min> <max>
Use the TYPE
command to check the type of value a key is mapping to:
<key>
I would suggest using TRUNCATE TABLE, it's quicker and uses less resources than DELETE FROM xxx
Here's the related MSDN article
Running git add
sometimes helps.
Git status is showing changed files and git diff is showing nothing...
> git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: package.json
no changes added to commit (use "git add" and/or "git commit -a")
> git diff
>
...running git add resolves the inconsistency.
> git add
> git status
On branch master
nothing to commit, working directory clean
>
You can also use html to override the css locally. I was having a similar issue and this worked for me:
<html>
<body>
<h4>A nested List:</h4>
<ul style="PADDING-LEFT: 12px">
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
</body>
</html>
Mark Longair's solution using git remote set-url...
is quite clear. You can also get the same behavior by directly editing this section of the .git/config file:
before:
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = git://github.com/my_user_name/my_repo.git
after:
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = [email protected]:my_user_name/my_repo.git
(And conversely, the git remote set-url...
invocation produces the above change.)
This is more of addendum to Kevin Dolan's answer than a complete answer, but I was having trouble extracting the type from the Number. This is my solution:
private Object handlePrimitive(JsonPrimitive json) {
if(json.isBoolean()) {
return json.getAsBoolean();
} else if(json.isString())
return json.getAsString();
}
Number num = element.getAsNumber();
if(num instanceof Integer){
map.put(fieldName, num.intValue());
} else if(num instanceof Long){
map.put(fieldName, num.longValue());
} else if(num instanceof Float){
map.put(fieldName, num.floatValue());
} else { // Double
map.put(fieldName, num.doubleValue());
}
}
This can mean a lot of things, but the most common one is that the class contained in the file doesn't have the same name as the file itself. So, check if your class is also called HelloWorld2.
In short, they are exactly the same. If you notice the end of the URL, sometimes you'll see .htm and other times you'll see .html. It still refers to the Hyper-Text Markup Language.
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
Recently I was working on a game compatible with CocoonJS with DOM limited to the canvas element - here is my approach:
Using fillText with a font that has not been loaded yet will execute properly but with no visual feedback - so the canvas plane will stay intact - all you have to do is periodically check the canvas for any changes (for example looping through getImageData searching for any non transparent pixel) that will happen when the font loads properly.
I have explained this technique a little bit more in my recent article http://rezoner.net/preloading-font-face-using-canvas,686
So this is a edge case. But if you need to load the JavaScript from a remote source, most modern browsers might block your cross-site requests due to CORS or something similar. So normal
<script src="https://another-domain.com/example.js"></script>
Won't work. And doing the document.createElement('script').src = '...'
won't cut it either. Instead, what you could do is load the java-script as a resource via standard GET
request, and do this:
<script type="text/javascript">
var script = document.createElement('script');
script.type = 'text/javascript';
let xhr = new XMLHttpRequest();
xhr.open("GET", 'https://raw.githubusercontent.com/Torxed/slimWebSocket/master/slimWebSocket.js', true);
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
script.innerHTML = this.responseText; // <-- This one
document.head.appendChild(script);
}
}
xhr.send();
</script>
By grabbing the content yourself, the browser won't notice malicious intents and allow you go do the request. Then you add it in <script>
's innerHTML
instead. This still causes the browser (at least tested in Chrome) to parse/execute the script.
Again, this is a edge case use case. And you'll have no backwards compatibility or browser compliance probably. But fun/useful thing to know about.
JAR File Manifest Attributes for Security
The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.
Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.
Permissions Attribute
The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.
Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:
sandbox - runs in the security sandbox and does not require additional permissions.
all-permissions - requires access to the user's system resources.
Changes to Security Slider:
The following changes to Security Slider were included in this release(7u51):
For more information, see Java Control Panel documentation.
sample MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet
Arrays in Java are of fixed size. What you'd need is an ArrayList, one of a number of extremely valuable Collections available in Java.
Instead of
Integer[] ints = new Integer[x]
you use
List<Integer> ints = new ArrayList<Integer>();
Then to change the list you use ints.add(y)
and ints.remove(z)
amongst many other handy methods you can find in the appropriate Javadocs.
I strongly recommend studying the Collections classes available in Java as they are very powerful and give you a lot of builtin functionality that Java-newbies tend to try to rewrite themselves unnecessarily.
Even if a builtin way existed, it wouldn't validate it as greater than today and it would differ very little from a substring call. I wouldn't worry about it.
I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.
Here's a simple way to test it:
public class OperatorTest {
public static void main(String[] args) {
boolean a = false;
a &= b();
}
private static boolean b() {
System.out.println("b() was called");
return true;
}
}
The output is b() was called
, therefore the right-hand operand is evaluated.
So, as already mentioned by others, a &= b
is the same as a = a & b
.
I ended up with this function to safely replace text without side effects (so far):
function replaceInText(element, pattern, replacement) {
for (let node of element.childNodes) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
replaceInText(node, pattern, replacement);
break;
case Node.TEXT_NODE:
node.textContent = node.textContent.replace(pattern, replacement);
break;
case Node.DOCUMENT_NODE:
replaceInText(node, pattern, replacement);
}
}
}
It's for cases where the 16kB of findAndReplaceDOMText
are a bit too heavy.
"SPL-way"
:
$splArray = SplFixedArray::fromArray($array);
$last_item_with_preserved_index[$splArray->getSize()-1] = $splArray->offsetGet($splArray->getSize()-1);
Read more about SplFixedArray
and why it's in some cases ( especially with big-index sizes array-data) more preferable than basic array
here => The SplFixedArray class.
Make Sure that you don't leave a space before <?php
when you start <?php
tag at the top of the page.
Since Spark 2.X
spark-csv
is integrated as native datasource. Therefore, the necessary statement simplifies to (windows)
df.write
.option("header", "true")
.csv("file:///C:/out.csv")
or UNIX
df.write
.option("header", "true")
.csv("/var/out.csv")
Notice: as the comments say, it is creating the directory by that name with the partitions in it, not a standard CSV file. This, however, is most likely what you want since otherwise your either crashing your driver (out of RAM) or you could be working with a non distributed environment.
The question is pretty old, but nowadays you can use forEach, which is efficient and will retain the keys as numbers:
let keys = widthRange.map((v,k) => k).filter(i=>i!==undefined))
This loops through widthRange and makes a new array with the value of the keys, and then filters out all sparce slots by only taking the values that are defined.
(Bad idea, but for thorughness: If slot 0 was always empty, that could be shortened to filter(i=>i)
or filter(Boolean)
And, it may be less efficient, but the numbers can be cast with let keys = Object.keys(array).map(i=>i*1)
I just encountered the same problem and it had to do with some files being lost or corrupted. To correct the issue, just run check disk:
chkdsk /F e:
This can be run from the search windows box or from a cmd prompt. The /F
fixes any issues it finds, like recovering the files. Once this finishes running, you can delete the files and folders like normal.
To dynamically change the color of a text box goto properties, goto font/Color and set the following expression
=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)
Same way for tolerance
=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")
One option that'll work with any version of PHP is to do what's already been suggested, which is something like this:
$eventTime = '2010-04-28 17:25:43';
$age = time() - strtotime($eventTime);
That will give you the age in seconds. From there, you can display it however you wish.
One problem with this approach, however, is that it won't take into account time shifts causes by DST. If that's not a concern, then go for it. Otherwise, you'll probably want to use the diff() method in the DateTime class. Unfortunately, this is only an option if you're on at least PHP 5.3.
Bit reversal in pseudo code
source -> byte to be reversed b00101100 destination -> reversed, also needs to be of unsigned type so sign bit is not propogated down
copy into temp so original is unaffected, also needs to be of unsigned type so that sign bit is not shifted in automaticaly
bytecopy = b0010110
LOOP8: //do this 8 times test if bytecopy is < 0 (negative)
set bit8 (msb) of reversed = reversed | b10000000
else do not set bit8
shift bytecopy left 1 place
bytecopy = bytecopy << 1 = b0101100 result
shift result right 1 place
reversed = reversed >> 1 = b00000000
8 times no then up^ LOOP8
8 times yes then done.
!important
word is prior to first two rules.for example:
.divclass .spanclass
is more specific than .spanclass
.divclass.divclass
is more specific than .divclass
#divId .spanclass
has ID that's why it is more specific than .divClass .spanClass
<div id="someDiv" style="color:red;">
has attribute and beats #someDiv{color:blue}
#someDiv{color:blue!important}
will be applied over attribute style="color:red"
Beginning with Android 3.2 (API level 13), size groups (folders small, normal, large, xlarge) are deprecated in favor of a new technique for managing screen sizes based on the available screen width.
You don't really have to do any registering as such. I've seen many programs, like emule, create their own protocol specificier (that's what I think it's called). After that, you basically just have to set some values in the registry as to what program handles that protocol. I'm not sure if there's any official registry of protocol specifiers. There isn't really much to stop you from creating your own protocol specifier for your own application if you want people to open your app from their browser.
Not relevant to the onclick issue, but also related:
For html attributes whose name collide with javascript reserved words, an alternate name is chosen, eg. <div class=''>
, but div.className
, or <label for='...'>
, but label.htmlFor
.
In reasonable browsers, this doesn't affect setAttribute
. So in gecko and webkit you'd call div.setAttribute('class', 'foo')
, but in IE you have to use the javascript property name instead, so div.setAttribute('className', 'foo')
.
public List<int> ConvertStringListToIntList(List<string> list)
{
List<int> resultList = new List<int>();
for (int i = 0; i < list.Count; i++)
resultList.Add(Convert.ToInt32(list[i]));
return resultList;
}
The correct syntax to install cron in cygwin as Windows service is to pass -n as argument and not -D:
cygrunsrv --install cron --path /usr/sbin/cron --args -n
-D returns usage error when starting cron in cygwin:
$
$cygrunsrv --install cron --path /usr/sbin/cron --args -D
$cygrunsrv --start cron
cygrunsrv: Error starting a service: QueryServiceStatus: Win32 error 1062:
The service has not been started.
$cat /var/log/cron.log
cron: unknown option -- D
usage: /usr/sbin/cron [-n] [-x [ext,sch,proc,parc,load,misc,test,bit]]
$
Below page has a good explanation.
Installing & Configuring the Cygwin Cron Service in Windows: https://www.davidjnice.com/cygwin_cron_service.html
P.S. I had to run Cygwin64 Terminal on my Windows 10 PC as administrator in order to install cron as Windows service.
The SQL is somewhat like the syntax of MS SQL.
SELECT * FROM [table$] WHERE *;
It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.
If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:
SELECT Name FROM [Users$] WHERE id = 1;
Hope this helps.
The most simple and shortest way to accomplish this:
/[^\p{L}\d\s@#]/u
[^...]
Match a single character not present in the list below
\p{L}
=> matches any kind of letter from any language
\d
=> matches a digit zero through nine
\s
=> matches any kind of invisible character
@#
=> @
and #
characters
Don't forget to pass the u
(unicode) flag.
Looks like you are doing this from scratch. Try using available reverse engineering tools like Netbeans Entities from Database to at least get the basics automated (like embedded ids). This can become a huge headache if you have many tables. I suggest avoid reinventing the wheel and use as many tools available as possible to reduce coding to the minimum and most important part, what you intent to do.
As library requires minSdkVersion 17
then you can change the same in build.gradle
(Module:Application) file:
defaultConfig {
minSdkVersion 17
targetSdkVersion 25
}
and after that building the project should not throw any build error.
Use Date.Now
instead of DateTime.Now
You can add the button image as follows:
CKEDITOR.plugins.add('showtime', //name of our plugin
{
requires: ['dialog'], //requires a dialog window
init:function(a) {
var b="showtime";
var c=a.addCommand(b,new CKEDITOR.dialogCommand(b));
c.modes={wysiwyg:1,source:1}; //Enable our plugin in both modes
c.canUndo=true;
//add new button to the editor
a.ui.addButton("showtime",
{
label:'Show current time',
command:b,
icon:this.path+"showtime.png" //path of the icon
});
CKEDITOR.dialog.add(b,this.path+"dialogs/ab.js") //path of our dialog file
}
});
Here is the actual plugin with all steps described.
The correct way to create a user in Django is to use the create_user function. This will handle the hashing of the password, etc..
from django.contrib.auth.models import User
user = User.objects.create_user(username='john',
email='[email protected]',
password='glass onion')
Using print
and JSON.stringify
you can simply produce a valid JSON
result.
Use --quiet
flag to filter shell noise from the output.
Use --norc
flag to avoid .mongorc.js
evaluation. (I had to do it because of a pretty-formatter that I use, which produces invalid JSON output)
Use DBQuery.shellBatchSize = ?
replacing ?
with the limit of the actual result to avoid paging.
And finally, use tee
to pipe the terminal output to a file:
// Shell:
mongo --quiet --norc ./query.js | tee ~/my_output.json
// query.js:
DBQuery.shellBatchSize = 2000;
function toPrint(data) {
print(JSON.stringify(data, null, 2));
}
toPrint(
db.getCollection('myCollection').find().toArray()
);
Hope this helps!
You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
mysql $link
generally means, the resource object of the established mysqli connection to query the database.
So there are two ways of solving this problem
mysqli_query();
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));
Or, Using mysql_query()
(This is now obselete)
$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());
As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .
The only tool I know is Vera. Haven't used it, though, so can't comment how viable it is. Demo looks promising.
You can use link-rewriting to append a unique identifier to all your URLs when starting at a single page (e.g. index.html/jsp/whatever). The browser will use the same cookies for all your tabs so everything you put in cookies will not be unique.
In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH
), using named ranges and the EVALUATE
function as I found from this link.
For example, I put the following terms as text in a cell, $G$1
:
"PRB", "utilization", "alignment", "spectrum"
Then, I defined a named range named search_terms
for that cell as described in the link above and shown in the figure below:
In the Refers to:
field I put the following:
=EVALUATE("{" & TDoc_List!$G$1 & "}")
The above EVALUATE
expression is simple used to emulate the literal string
{"PRB", "utilization", "alignment", "spectrum"}
to be used as input to the SEARCH
function: using a direct reference to the SINGLE cell $G$1
(augmented with the curly braces in that case) inside SEARCH
does not work, hence the use of named ranges and EVALUATE
.
The trick now consists in replacing the direct reference to $G$1
by the EVALUATE
-augmented named range search_terms
.
It really works, and shows once more how powerful Excel really is!
Hope this helps.
A quick and easy solution for interactive work is to copy-and-paste the text by loading the data from the clipboard.
Select the content of the string with your mouse:
In the Python shell use read_clipboard()
>>> pd.read_clipboard()
col1;col2;col3
0 1;4.4;99
1 2;4.5;200
2 3;4.7;65
3 4;3.2;140
Use the appropriate separator:
>>> pd.read_clipboard(sep=';')
col1 col2 col3
0 1 4.4 99
1 2 4.5 200
2 3 4.7 65
3 4 3.2 140
>>> df = pd.read_clipboard(sep=';') # save to dataframe
Replace this :
$('#subscription_order_form').submit(function(e){
e.preventDefault();
});
with this:
$('#subscription_order_form').on('keydown', function(e){
if (e.which===13) e.preventDefault();
});
That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.
The CSS property touch-action may get you what you are looking for, though it may not work in all your target browsers.
html, body {
width: 100%; height: 100%;
overflow: hidden;
touch-action: none;
}
I experienced the same problem while trying to write a code concerning Speech_to_Text.
The solution was very simple. Uninstall the previous pywin32 using the pip method
pip uninstall pywin32
The above will remove the existing one which is by default for 32 bit computers. And install it again using
pip install pywin32
This will install the one for the 64 bit computer which you are using.
Upgrading to latest gradle plugin solve my problem :
classpath 'com.android.tools.build:gradle:0.13.+'
Output from subprocess.call()
should only be redirected to files.
You should use subprocess.Popen()
instead. Then you can pass subprocess.PIPE
for the stderr, stdout, and/or stdin parameters and read from the pipes by using the communicate()
method:
from subprocess import Popen, PIPE
p = Popen(['program', 'arg1'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode
The reasoning is that the file-like object used by subprocess.call()
must have a real file descriptor, and thus implement the fileno()
method. Just using any file-like object won't do the trick.
See here for more info.
If after calling "csrutil disabled" still your command does not work, try with "sudo" in terminal, for example:
sudo mv geckodriver /usr/local/bin
And it should work.
If you don't want to open Android Studio just to modify your path...
${HOME}/Library/Android/sdk/tools
${HOME}/Library/Android/sdk/platform-tools
.bashwhatever
export PATH="${HOME}/Library/Android/sdk/tools:${HOME}/Library/Android/sdk/platform-tools:${PATH}"
Also note that you cannot normally set a value for an IDENTITY column. You can, however, specify the identity of rows if you set IDENTITY_INSERT to ON for your table. For example:
SET IDENTITY_INSERT Orders ON
-- do inserts here
SET IDENTITY_INSERT Orders OFF
This insert will reset the identity to the last inserted value. From MSDN:
If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.
Get the public key from the client phone (adb host)
cat /data/.android/adbkey.pub
copy the above public key to the target phone's /data/misc/adb/adb_keys
location. (you may need to stop the adb daemon first with stop adbd
)
cat /data/misc/adb/adb_keys
verify both cat
outputs match.
try restarting adb daemon on target start adbd
or just reboot them.
If you are having problems reading or writing to ADB KEYS in above steps, try setting environment variable ADB_KEYS_PATH
with a temporary path (eg: /data/local/tmp
). Refer to that link it goes into more details
"On the host, the user public/private key pair is automatically generated,
if it does not exist, when the adb daemon starts and is stored in
$HOME/.android/adb_key(.pub) or in $ANDROID_SDK_HOME on windows. If needed,
the ADB_KEYS_PATH env variable may be set to a :-separated (; under
Windows) list of private keys, e.g. company-wide or vendor keys.
On the device, vendors public keys are installed at build time in
/adb_keys. User-installed keys are stored in /data/misc/adb/adb_keys"
list( map( lambda x: x[4][0], socket.getaddrinfo( \
'www.example.com.',22,type=socket.SOCK_STREAM)))
gives you a list of the addresses for www.example.com. (ipv4 and ipv6)
So before MySQL 8.0 there is no ROW_NUMBER() function. Accpted answer rewritten to support older versions of MySQL:
SET @row_number = 0;
SELECT t.A, t.B, t.C, (@row_number:=@row_number + 1) AS number
FROM dbo.tableZ AS t ORDER BY t.A;
For people looking to do if statements with multiple 'or' values.
<div ng-if="::(a || b || c || d || e || f)"><div>
Calling readOnly=false from readOnly=true doesn't work since the previous transaction continues.
In your example, the handle() method on your service layer is starting a new read-write transaction. If the handle method in turn calls service methods that annotated read-only, the read-only will take no effect as they will participate in the existing read-write transaction instead.
If it is essential for those methods to be read-only, then you can annotate them with Propagation.REQUIRES_NEW, and they will then start a new read-only transaction rather than participate in the existing read-write transaction.
Here is a worked example, CircuitStateRepository is a spring-data JPA repository.
BeanS calls a transactional=read-only Bean1, which does a lookup and calls transactional=read-write Bean2 which saves a new object.
31 09:39:44.199 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name [nz.co.vodafone.wcim.business.Bean1.startSomething]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
Bean 2 pariticipates in it.
31 09:39:44.230 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Participating in existing transaction
Nothing is committed to the database.
Now change Bean2 @Transactional
annotation to add propagation=Propagation.REQUIRES_NEW
Bean1 starts a read-only tx.
31 09:31:36.418 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name [nz.co.vodafone.wcim.business.Bean1.startSomething]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
Bean2 starts a new read-write tx
31 09:31:36.449 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Suspending current transaction, creating new transaction with name [nz.co.vodafone.wcim.business.Bean2.createSomething]
And the changes made by Bean2 are now committed to the database.
Here's the example, tested with spring-data, hibernate and oracle.
@Named
public class BeanS {
@Inject
Bean1 bean1;
@Scheduled(fixedRate = 20000)
public void runSomething() {
bean1.startSomething();
}
}
@Named
@Transactional(readOnly = true)
public class Bean1 {
Logger log = LoggerFactory.getLogger(Bean1.class);
@Inject
private CircuitStateRepository csr;
@Inject
private Bean2 bean2;
public void startSomething() {
Iterable<CircuitState> s = csr.findAll();
CircuitState c = s.iterator().next();
log.info("GOT CIRCUIT {}", c.getCircuitId());
bean2.createSomething(c.getCircuitId());
}
}
@Named
@Transactional(readOnly = false)
public class Bean2 {
@Inject
CircuitStateRepository csr;
public void createSomething(String circuitId) {
CircuitState c = new CircuitState(circuitId + "-New-" + new DateTime().toString("hhmmss"), new DateTime());
csr.save(c);
}
}
It's easy (For Chorme only)
.woff
format) > open link in new tab (this should download the font in .woff
formatIt waits for client.GetAsync("aaaaa");
, but doesn't wait for result = Print(x)
Try responseTask.ContinueWith(x => result = Print(x)).Wait()
--EDIT--
Task responseTask = Task.Run(() => {
Thread.Sleep(1000);
Console.WriteLine("In task");
});
responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
responseTask.Wait();
Console.WriteLine("End");
Above code doesn't guarantee the output:
In task
In ContinueWith
End
But this does (see the newTask
)
Task responseTask = Task.Run(() => {
Thread.Sleep(1000);
Console.WriteLine("In task");
});
Task newTask = responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
newTask.Wait();
Console.WriteLine("End");
Here is a good choice for gradients for both platforms iOS and Android:
https://github.com/react-native-community/react-native-linear-gradient
There are others approaches like expo, however react-native-linear-gradient have worked better for me.
<LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']} style={styles.linearGradient}>
<Text style={styles.buttonText}>
Sign in with Facebook
</Text>
</LinearGradient>
// Later on in your styles..
var styles = StyleSheet.create({
linearGradient: {
flex: 1,
paddingLeft: 15,
paddingRight: 15,
borderRadius: 5
},
buttonText: {
fontSize: 18,
fontFamily: 'Gill Sans',
textAlign: 'center',
margin: 10,
color: '#ffffff',
backgroundColor: 'transparent',
},
});
If you need locale-aware number formatting, use QLocale::toString instead.
You can use the target
argument in the Thread
constructor to directly pass in a function that gets called instead of run
.
The following automatically uses the best precision:
/**
* Compare to floats for (almost) equality. Will check whether they are
* at most 5 ULP apart.
*/
public static boolean isFloatingEqual(float v1, float v2) {
if (v1 == v2)
return true;
float absoluteDifference = Math.abs(v1 - v2);
float maxUlp = Math.max(Math.ulp(v1), Math.ulp(v2));
return absoluteDifference < 5 * maxUlp;
}
Of course, you might choose more or less than 5 ULPs (‘unit in the last place’).
If you’re into the Apache Commons library, the Precision
class has compareTo()
and equals()
with both epsilon and ULP.
Run this:
SELECT CASE transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'ReadUncommitted'
WHEN 2 THEN 'ReadCommitted'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL
FROM sys.dm_exec_sessions
where session_id = @@SPID
Here's a one-liner using sschober
's tool.
$ while true; do kqwait ./file-to-watch.js; script-to-execute.sh; done
This are to way to bind add too numbers
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script>_x000D_
_x000D_
var app = angular.module("myApp", []);_x000D_
_x000D_
app.controller("myCtrl", function($scope) {_x000D_
$scope.total = function() { _x000D_
return parseInt($scope.num1) + parseInt($scope.num2) _x000D_
}_x000D_
})_x000D_
</script>_x000D_
<body ng-app='myApp' ng-controller='myCtrl'>_x000D_
_x000D_
<input type="number" ng-model="num1">_x000D_
<input type="number" ng-model="num2">_x000D_
Total:{{num1+num2}}_x000D_
_x000D_
Total: {{total() }}_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
How about accepting complex roots as solutions?
import math
# User inserting the values of a, b and c
a = float(input("Insert coefficient a: "))
b = float(input("Insert coefficient b: "))
c = float(input("Insert coefficient c: "))
discriminant = b**2 - 4 * a * c
if discriminant >= 0:
x_1=(-b+math.sqrt(discriminant))/2*a
x_2=(-b-math.sqrt(discriminant))/2*a
else:
x_1= complex((-b/(2*a)),math.sqrt(-discriminant)/(2*a))
x_2= complex((-b/(2*a)),-math.sqrt(-discriminant)/(2*a))
if discriminant > 0:
print("The function has two distinct real roots: ", x_1, " and ", x_2)
elif discriminant == 0:
print("The function has one double root: ", x_1)
else:
print("The function has two complex (conjugate) roots: ", x_1, " and ", x_2)
just remove s from the permission you are using sss you have to use ss
Eclipse Collections has Pair
and all combinations of primitive/object Pairs (for all eight primitives).
The Tuples
factory can create instances of Pair
, and the PrimitiveTuples
factory can be used to create all combinations of primitive/object pairs.
We added these before Java 8 was released. They were useful to implement key/value Iterators for our primitive maps, which we also support in all primitive/object combinations.
If you're willing to add the extra library overhead, you can use Stuart's accepted solution and collect the results into a primitive IntList
to avoid boxing. We added new methods in Eclipse Collections 9.0 to allow for Int/Long/Double
collections to be created from Int/Long/Double
Streams.
IntList list = IntLists.mutable.withAll(intStream);
Note: I am a committer for Eclipse Collections.
There are two important points to the Swift 2 error handling model: exhaustiveness and resiliency. Together, they boil down to your do
/catch
statement needing to catch every possible error, not just the ones you know you can throw.
Notice that you don't declare what types of errors a function can throw, only whether it throws at all. It's a zero-one-infinity sort of problem: as someone defining a function for others (including your future self) to use, you don't want to have to make every client of your function adapt to every change in the implementation of your function, including what errors it can throw. You want code that calls your function to be resilient to such change.
Because your function can't say what kind of errors it throws (or might throw in the future), the catch
blocks that catch it errors don't know what types of errors it might throw. So, in addition to handling the error types you know about, you need to handle the ones you don't with a universal catch
statement -- that way if your function changes the set of errors it throws in the future, callers will still catch its errors.
do {
let sandwich = try makeMeSandwich(kitchen)
print("i eat it \(sandwich)")
} catch SandwichError.NotMe {
print("Not me error")
} catch SandwichError.DoItYourself {
print("do it error")
} catch let error {
print(error.localizedDescription)
}
But let's not stop there. Think about this resilience idea some more. The way you've designed your sandwich, you have to describe errors in every place where you use them. That means that whenever you change the set of error cases, you have to change every place that uses them... not very fun.
The idea behind defining your own error types is to let you centralize things like that. You could define a description
method for your errors:
extension SandwichError: CustomStringConvertible {
var description: String {
switch self {
case NotMe: return "Not me error"
case DoItYourself: return "Try sudo"
}
}
}
And then your error handling code can ask your error type to describe itself -- now every place where you handle errors can use the same code, and handle possible future error cases, too.
do {
let sandwich = try makeMeSandwich(kitchen)
print("i eat it \(sandwich)")
} catch let error as SandwichError {
print(error.description)
} catch {
print("i dunno")
}
This also paves the way for error types (or extensions on them) to support other ways of reporting errors -- for example, you could have an extension on your error type that knows how to present a UIAlertController
for reporting the error to an iOS user.
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
This site has two pretty simple solutions - just check the code, I provided the descriptions in case you wanted them - saves you some clicks.
http://www.richardlord.net/blog/dates-in-php-and-mysql
1.One common solution is to store the dates in DATETIME fields and use PHPs date() and strtotime() functions to convert between PHP timestamps and MySQL DATETIMEs. The methods would be used as follows -
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
$phpdate = strtotime( $mysqldate );
2.Our second option is to let MySQL do the work. MySQL has functions we can use to convert the data at the point where we access the database. UNIX_TIMESTAMP will convert from DATETIME to PHP timestamp and FROM_UNIXTIME will convert from PHP timestamp to DATETIME. The methods are used within the SQL query. So we insert and update dates using queries like this -
$query = "UPDATE table SET
datetimefield = FROM_UNIXTIME($phpdate)
WHERE...";
$query = "SELECT UNIX_TIMESTAMP(datetimefield)
FROM table WHERE...";
I'm not exactly sure what it is that you want. Do you want a TimeStamp? Then you can do something simple like:
TimeStamp ts = TimeStamp.FromTicks(value.ToUniversalTime().Ticks);
Since you named a variable epoch, do you want the Unix time equivalent of your date?
DateTime unixStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
long epoch = (long)Math.Floor((value.ToUniversalTime() - unixStart).TotalSeconds);
For me the fix was removing the node* packages and also the npm packages.
Then a fresh install as:
sudo apt-get install autoclean
sudo apt-get install nodejs-legacy
npm install
Inheritance is pretty enticing especially coming from procedural-land and it often looks deceptively elegant. I mean all I need to do is add this one bit of functionality to some other class, right? Well, one of the problems is that
Your base class breaks encapsulation by exposing implementation details to subclasses in the form of protected members. This makes your system rigid and fragile. The more tragic flaw however is the new subclass brings with it all the baggage and opinion of the inheritance chain.
The article, Inheritance is Evil: The Epic Fail of the DataAnnotationsModelBinder, walks through an example of this in C#. It shows the use of inheritance when composition should have been used and how it could be refactored.
According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location
rather than document.location
.
This is the right way to do. You can try this code.
#include <iostream>
using namespace std;
class T1 {
const int t;
public:
T1():t(100) {
cout << "T1 constructor: " << t << endl;
}
};
int main() {
T1 obj;
return 0;
}
if you are using C++10 Compiler or below
then you can not initialize the cons member at the time of declaration. So here it is must to make constructor to initialise the const data member. It is also must to use initialiser list T1():t(100)
to get memory at instant.
Just escape the dashes to prevent them from being interpreted (I don't think underscore needs escaping, but it can't hurt). You don't say which regex you are using.
([A-Za-z0-9\-\_]+)
1- There is no way to actually destroy an object in javascript, but using delete
, we could remove a reference from an object:
var obj = {};
obj.mypointer = null;
delete obj.mypointer;
2- The important point about the delete
keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete
keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.
3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}]
overriding the value of the array like array = []
would remove the references to the two objects inside the array and those two objects would be marked as collectible.
4- for your solution the easiest way is just this:
var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;
As mentioned above, either setting storage.instance = null
or delete storage.instance
would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null
then the storage object still has a property called instance (with the value null). If you delete storage.instance
then the storage object no longer has a property named instance.
and WHAT ABOUT destroy method ??
the paradoxical point here is if you use instance.destroy
in the destroy function you have no access to the actual instance
pointer, and it won't let you delete it.
The only way is to pass the reference to the destroy function and then delete it:
// Class constructor
var Class = function () {
this.destroy = function (baseObject, refName) {
delete baseObject[refName];
};
};
// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined
BUT if I were you I would simply stick to the first solution and delete the object like this:
storage.instance = null;
// OR
delete storage.instance;
WOW it was too much :)
You need to delete your old db folder and recreate new one. It will resolve your issue.
Simply do it.
this.state={f_name:""};
textChangeHandler = async (key, val) => {
await this.setState({ [key]: val });
}
<Textfield onChangeText={val => this.textChangeHandler('f_name', val)}>
modify from Peter Olson's answer: https://stackoverflow.com/a/8085118
!obj || (typeof obj === 'string'
var findObjectByKeyVal= function (obj, key, val) {
if (!obj || (typeof obj === 'string')) {
return null
}
if (obj[key] === val) {
return obj
}
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
var found = findObjectByKeyVal(obj[i], key, val)
if (found) {
return found
}
}
}
return null
}
You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP
(I recommend the more explicit MSXML2.XMLHTTP.3.0
progID) however you may need to do different things with the response, it may not be text.
The XMLHTTP also has a responseBody
property which is a byte array version of the reponse and there is a responseStream
which is an IStream
wrapper for the response.
Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0
or WinHttp.WinHttpRequest.5.1
(which has a near identical interface).
Here is an example of using XmlHttp to fetch a PDF file and store it:-
Dim oXMLHTTP
Dim oStream
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")
oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send
If oXMLHTTP.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write oXMLHTTP.responseBody
oStream.SaveToFile "c:\somefolder\file.pdf"
oStream.Close
End If
In Android Studio your resource(images) file name cannot start with NUMERIC
and It cannot contain any BIG
character. To solve your problem, do as Aliyah said. Just restart your IDE. This solved my problem too.
More accurately, your mod1
and lib
directories are not modules, they are packages. The file mod11.py
is a module.
Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.
>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()
mod12
An alternative is to use the from
syntax to "pull" a module from a package into you scripts namespace.
>>> from lib.pkg1 import mod11
Then reference the function as simply mod11.mod12()
.
No one mentioned yet streams added in Java 8 so here it goes:
int[] array = list.stream().mapToInt(i->i).toArray();
//OR
//int[] array = list.stream().mapToInt(Integer::intValue).toArray();
Thought process:
simple Stream#toArray
returns Object[]
, so it is not what we want. Also Stream#toArray(IntFunction<A[]> generator)
doesn't do what we want because generic type A
can't represent primitive int
so it would be nice to have some stream which could handle primitive type int
instead of wrapper Integer
, because its toArray
method will most likely also return int[]
array (returning something else like Object[]
or even boxed Integer[]
would be unnatural here). And fortunately Java 8 has such stream which is IntStream
so now only thing we need to figure out is how to convert our Stream<Integer>
(which will be returned from list.stream()
) to that shiny IntStream
. Here Stream#mapToInt(ToIntFunction<? super T> mapper)
method comes to a rescue. All we need to do is pass to it mapping from Integer
to int
. We could use something like Integer#intValue
which returns int
like :
mapToInt( (Integer i) -> i.intValue() )
(or if someone prefers mapToInt(Integer::intValue)
)
but similar code can be generated using unboxing, since compiler knows that result of this lambda must be int
(lambda in mapToInt
is implementation of ToIntFunction
interface which expects body for int applyAsInt(T value)
method which is expected to return int
).
So we can simply write
mapToInt((Integer i)->i)
Also since Integer
type in (Integer i)
can be inferred by compiler because List<Integer>#stream()
returns Stream<Integer>
we can also skip it which leaves us with
mapToInt(i -> i)
I got the same problem. However, finally, I can fix it. Currently, I use Visual Studio 2013 Community Edition. I just use Add->Existing Item... and browse to where the SQLite.Data.SQLite files are in (my case is 'C:\Program Files (x86)\System.Data.SQLite\2013\bin'). Please don't forget to change type of what you will include to Assembly Files (*.dll; *.pdb). Choose 'SQLite.Interop.dll' in that folder. From there and then, I can continue without any problems at all. Good luck to you all. ^_^ P.S. I create web form application. I haven't tried in window form application or others yet.
Incase you are dynamically getting your data e.g When you need data based on the user logged in by their id use consider the following code example for a No Active Record:
$this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id'));
return $query->row_array();
This will return a specific row based on your the set session data of user.
Try this Demo
HTML
<table>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
</tr>
</table>
CSS
td:nth-of-type(2) {
padding-right: 10px;
}
this works in ubuntu 18 and above (not tested in previous versions):
sudo apt install python3-virtualenv
For me, adding <script>window.print();</script>
to the end of the page worked.
I didn't need the type="text/javascript"
attribute, or even for the page to be wrapped in a <body>
tag. However, all of my previous attempts to intuitively use the answers suggested here, of just writing window.onload=window.print
or longer versions such as window.onload=()=>window.print();
did not work, and of course calling print on the newly created window does not wait for the contents to load.
why not just use a button instead of submit. clicking the button will let you construct a proper url for your browser to redirect to.
$("#button").click(function() {
var url = 'site.com/process.php?';
$('form input').each(function() {
url += 'key=' + $(this).val() + "&";
});
// handle removal of last &.
window.location.replace(url);
});
Try something like:
$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
event.preventDefault();
$(this).next('div').slideToggle(200);
});
Here is the page about that in the jQuery documentation
While these answers are correct, they are more mathematically intense than necessary. Assume map coordinates, where the most north point is the highest point on the map. Find the most north point, and if 2 points tie, it is the most north then the most east (this is the point that lhf uses in his answer). In your points,
point[0] = (5,0)
point[1] = (6,4)
point[2] = (4,5)
point[3] = (1,5)
point[4] = (1,0)
If we assume that P2 is the most north then east point either the previous or next point determine clockwise, CW, or CCW. Since the most north point is on the north face, if the P1 (previous) to P2 moves east the direction is CW. In this case, it moves west, so the direction is CCW as the accepted answer says. If the previous point has no horizontal movement, then the same system applies to the next point, P3. If P3 is west of P2, it is, then the movement is CCW. If the P2 to P3 movement is east, it's west in this case, the movement is CW. Assume that nte, P2 in your data, is the most north then east point and the prv is the previous point, P1 in your data, and nxt is the next point, P3 in your data, and [0] is horizontal or east/west where west is less than east, and [1] is vertical.
if (nte[0] >= prv[0] && nxt[0] >= nte[0]) return(CW);
if (nte[0] <= prv[0] && nxt[0] <= nte[0]) return(CCW);
// Okay, it's not easy-peasy, so now, do the math
if (nte[0] * nxt[1] - nte[1] * nxt[0] - prv[0] * (nxt[1] - crt[1]) + prv[1] * (nxt[0] - nte[0]) >= 0) return(CCW); // For quadrant 3 return(CW)
return(CW) // For quadrant 3 return (CCW)
I had a similar problem setting up eclipse in the office. I had set up the for HTTP, HTTPS and SOCKS in:
Window>pref>general>network connections
Clearing the proxy settings for SOCKS fixed the problem for me.
on ubuntu 18.04 in etc/phpmyadmin/config.inc.php
comment all the block
Optional: User for advanced features
Open your terminal and type the following command to add anaconda to environment path
for anaconda 2 :
export PATH=~/anaconda2/bin:$PATH
for anaconda 3 :
export PATH=~/anaconda3/bin:$PATH
Then to check the conda version just type,
conda --version
Create an environment using the following command,
conda create --name myenv
Activate the source using,
source activate myenv
Then your anaconda IDE is ready!!!
final Map<String, String> mss1 = new ProcessBuilder().environment();
mss1.entrySet()
.stream()
//depending on how you want to join K and V use different delimiter
.map(entry ->
String.join(":", entry.getKey(),entry.getValue()))
.forEach(System.out::println);
you can copy an individual text apart from an HTML element's text.
var copyToClipboard = function (text) {
var $txt = $('<textarea />');
$txt.val(text)
.css({ width: "1px", height: "1px" })
.appendTo('body');
$txt.select();
if (document.execCommand('copy')) {
$txt.remove();
}
};
I had a case where I would take photos of clients online and would need to update the div if a photo is changed. Browser was still showing the old photo. So I used the hack of calling a random GET variable, which would be unique every time. Here it is if it could help anybody
<img src="/photos/userid_73.jpg?random=<?php echo rand() ?>" ...
EDIT As pointed out by others, following is much more efficient solution since it will reload images only when they are changed, identifying this change by the file size:
<img src="/photos/userid_73.jpg?modified=<? filemtime("/photos/userid_73.jpg")?>"
select from_unixtime( 600 * ( unix_timestamp( [Date] ) % 600 ) ) AS RecT, avg(Value)
from [FRIIB].[dbo].[ArchiveAnalog]
group by RecT
order by RecT;
replace the two 600 by any number of seconds you want to group.
If you need this often and the table doesn't change, as the name Archive suggests, it would probably be a bit faster to convert and store the date (& time) as a unixtime in the table.
Another solution could be:
<script>
$(document)
.ready(
function() {
var wrapper = $(".myFields");
$(add_button)
.click(
function(e) {
e.preventDefault();
$(wrapper)
.append(
'.....'); //add fields here
});
$(wrapper).on("click", ".delFld", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
</script>
Source: Here
I like to remove missing values from a list like this:
list_no_nan = [x for x in list_with_nan if pd.notnull(x)]
Just think of it as the "starting point".
In a sense of object-oriented programming, say C#, it's the init() or constructor of the object class, that's what "entry point" meant.
For example
public class IamMain // when export and require this guy
{
public IamMain() // this is "main"
{...}
... // many others such as function, properties, etc.
}
Display your file first and set its value into url.
index.php
<a href="download.php?download='.$row['file'].'" title="Download File">
download.php
<?php
/*db connectors*/
include('dbconfig.php');
/*function to set your files*/
function output_file($file, $name, $mime_type='')
{
if(!is_readable($file)) die('File not found or inaccessible!');
$size = filesize($file);
$name = rawurldecode($name);
$known_mime_types=array(
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"jpg" => "image/jpg",
"php" => "text/plain",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"pdf" => "application/pdf",
"txt" => "text/plain",
"html"=> "text/html",
"png" => "image/png",
"jpeg"=> "image/jpg"
);
if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
} else {
$mime_type="application/force-download";
};
};
@ob_end_clean();
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}
$chunksize = 1*(1024*1024);
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);
while(!feof($file) &&
(!connection_aborted()) &&
($bytes_send<$new_length)
)
{
$buffer = fread($file, $chunksize);
echo($buffer);
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else
die('Error - can not open file.');
die();
}
set_time_limit(0);
/*set your folder*/
$file_path='uploads/'."your file";
/*output must be folder/yourfile*/
output_file($file_path, ''."your file".'', $row['type']);
/*back to index.php while downloading*/
header('Location:index.php');
?>
Please delete package-lock.json
and clear npm cache with npm cache clear --force
and delete whole node_modules
directory
Finally install or update packages again with npm install
/ npm update
You can also add any new packages with npm install <package-name>
This fixed for me.
Thanks and happy coding.
Other answers already cover how to filter by an address, but if you would like to exclude an address use
ip.addr < 192.168.0.11
From Java 9, you can use the stream provided by Matcher.results()
long matches = matcher.results().count();
As I mentioned in my comment, I think the reason why this doesn't work is because the compiler can't infer types based on generic constraints.
Below is an alternative implementation that will compile. I've revised the IAccess interface to only have the T
generic type parameter.
interface ISignatur<T>
{
Type Type { get; }
}
interface IAccess<T>
{
ISignatur<T> Signature { get; }
T Value { get; set; }
}
class Signatur : ISignatur<bool>
{
public Type Type
{
get { return typeof(bool); }
}
}
class ServiceGate
{
public IAccess<T> Get<T>(ISignatur<T> sig)
{
throw new NotImplementedException();
}
}
static class Test
{
static void Main()
{
ServiceGate service = new ServiceGate();
var access = service.Get(new Signatur());
}
}
Here's one way to do it—there are many others:
bool b[4];
int v = 7; // number to dissect
for (int j = 0; j < 4; ++j)
b [j] = 0 != (v & (1 << j));
It is hard to understand why use of a loop is not desired, but it is easy enough to unroll the loop:
bool b[4];
int v = 7; // number to dissect
b [0] = 0 != (v & (1 << 0));
b [1] = 0 != (v & (1 << 1));
b [2] = 0 != (v & (1 << 2));
b [3] = 0 != (v & (1 << 3));
Or evaluating constant expressions in the last four statements:
b [0] = 0 != (v & 1);
b [1] = 0 != (v & 2);
b [2] = 0 != (v & 4);
b [3] = 0 != (v & 8);
You want $.param()
: http://api.jquery.com/jQuery.param/
Specifically, you want this:
var data = { one: 'first', two: 'second' };
var result = $.param(data);
When given something like this:
{a: 1, b : 23, c : "te!@#st"}
$.param
will return this:
a=1&b=23&c=te!%40%23st
Well, just do what the error message tells you.
Don't call setContentView()
before requestFeature()
.
Note:
As said in comments, for both ActionBarSherlock
and AppCompat
library, it's necessary to call requestFeature()
before super.onCreate()
Based on the answer of Arseniy-II: I had the Use-Case where the scrolling entity was not window itself but a inner Template (in this case a div). In this scenario we need to set an ID for the scrolling container and get it via getElementById
to use its scrolling function:
<div class="scroll-container" id="app-content">
...
</div>
const yOffsetForScroll = -100
const y = document.getElementById(this.idToScroll).getBoundingClientRect().top;
const main = document.getElementById('app-content');
main.scrollTo({
top: y + main.scrollTop + yOffsetForScroll,
behavior: 'smooth'
});
Leaving it here in case someone faces a similar situation!
osx could be using launchctl to launch mysql. Try this:
sudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysqld.plist
You append a newline to both the username and the password, i.e. the output would be something like
Sebastian
password
John
hfsjaijn
use fwrite($fh,$user." ".$password."\n");
instead to have them both on one line.
Or use fputcsv() to write the data and fgetcsv()
to fetch it. This way you would at least avoid encoding problems like e.g. with $username='Charles, III';
...i.e. setting aside all the things that are wrong about storing plain passwords in plain files and using _GET for this type of operation (use _POST instead) ;-)
Observations on an interesting Switch case
trap --> fall through
of switch
"The break statements are necessary because without them, statements in switch blocks fall through:" Java Doc's example
Snippet of consecutive case
without break
:
char c = 'A';/* switch with lower case */;
switch(c) {
case 'a':
System.out.println("a");
case 'A':
System.out.println("A");
break;
}
O/P for this case is:
A
But if you change value of c, i.e., char c = 'a';
, then this get interesting.
O/P for this case is:
a
A
Even though the 2nd case test fails, program goes onto print A
, due to missing break
which causes switch
to treat the rest of the code as a block. All statements after the matching case label are executed in sequence.
If you have a list of lists (tracked_output_sheet in my case), where you want to delete last element from each list, you can use the following code:
interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim
Yes it is possible if you bind events using tag attribute onclick="sayHi()"
directly in template similar like your <body onload="start()">
- this approach similar to frameworks angular/vue/react/etc. You can also use <template>
to operate on 'dynamic' html like here. It is not strict unobtrusive js however it is acceptable for small projects
function start() {_x000D_
mydiv.innerHTML += "bar";_x000D_
}_x000D_
_x000D_
function sayHi() {_x000D_
alert("hi");_x000D_
}
_x000D_
<body onload="start()">_x000D_
<div id="mydiv" style="border: solid red 2px">_x000D_
<span id="myspan" onclick="sayHi()">foo</span>_x000D_
</div>_x000D_
</body>
_x000D_
Here I am going to explain not only the GROUP clause use, but also the Aggregate functions use.
The GROUP BY
clause is used in conjunction with the aggregate functions to group the result-set by one or more columns. e.g.:
-- GROUP BY with one parameter:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
-- GROUP BY with two parameters:
SELECT
column_name1,
column_name2,
AGGREGATE_FUNCTION(column_name3)
FROM
table_name
GROUP BY
column_name1,
column_name2;
Remember this order:
SELECT (is used to select data from a database)
FROM (clause is used to list the tables)
WHERE (clause is used to filter records)
GROUP BY (clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns)
HAVING (clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE)
ORDER BY (keyword is used to sort the result-set)
You can use all of these if you are using aggregate functions, and this is the order that they must be set, otherwise you can get an error.
Aggregate Functions are:
MIN() returns the smallest value in a given column
MAX() returns the maximum value in a given column.
SUM() returns the sum of the numeric values in a given column
AVG() returns the average value of a given column
COUNT() returns the total number of values in a given column
COUNT(*) returns the number of rows in a table
SQL script examples about using aggregate functions:
Let's say we need to find the sale orders whose total sale is greater than $950. We combine the HAVING
clause and the GROUP BY
clause to accomplish this:
SELECT
orderId, SUM(unitPrice * qty) Total
FROM
OrderDetails
GROUP BY orderId
HAVING Total > 950;
Counting all orders and grouping them customerID and sorting the result ascendant. We combine the COUNT
function and the GROUP BY
, ORDER BY
clauses and ASC
:
SELECT
customerId, COUNT(*)
FROM
Orders
GROUP BY customerId
ORDER BY COUNT(*) ASC;
Retrieve the category that has an average Unit Price greater than $10, using AVG
function combine with GROUP BY
and HAVING
clauses:
SELECT
categoryName, AVG(unitPrice)
FROM
Products p
INNER JOIN
Categories c ON c.categoryId = p.categoryId
GROUP BY categoryName
HAVING AVG(unitPrice) > 10;
Getting the less expensive product by each category, using the MIN
function in a subquery:
SELECT categoryId,
productId,
productName,
unitPrice
FROM Products p1
WHERE unitPrice = (
SELECT MIN(unitPrice)
FROM Products p2
WHERE p2.categoryId = p1.categoryId)
The following statement groups rows with the same values in both categoryId and productId columns:
SELECT
categoryId, categoryName, productId, SUM(unitPrice)
FROM
Products p
INNER JOIN
Categories c ON c.categoryId = p.categoryId
GROUP BY categoryId, productId
WHERE DATEDIFF(day, tstamp, @dateParam) = 0
This should get you there if you don't care about time.
This is to answer the meta question of comparing the dates of two values when you don't care about the time.
I had the same issue and was able to resolve it by manually removing the MapFragment
in the onDestroy()
method of the Fragment
class. Here is code that works and references the MapFragment
by ID in the XML:
@Override
public void onDestroyView() {
super.onDestroyView();
MapFragment f = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
If you don't remove the MapFragment
manually, it will hang around so that it doesn't cost a lot of resources to recreate/show the map view again. It seems that keeping the underlying MapView
is great for switching back and forth between tabs, but when used in fragments this behavior causes a duplicate MapView
to be created upon each new MapFragment
with the same ID. The solution is to manually remove the MapFragment
and thus recreate the underlying map each time the fragment is inflated.
I also noted this in another answer [1].
As long as it's supposed to return a reference to the object, returning a NULL should be good.
However, if it's returning the whole bloody thing (like in C++ if you do: 'return blah;' rather than 'return &blah;' (or 'blah' is a pointer), then you can't return a NULL, because it's not of type 'object'. In that case, throwing an exception, or returning a blank object that doesn't have a success flag set is how I would approach the problem.
I think you've missed the point of access control.
A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.
Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee
) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.
In your specific case, it seems that paste.ee
doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).
on Mac, how I usually solve it
Hope this helps OP or someone else reading
I've always thought that Encryption can be converted both ways, in a way that the end value can bring you to original value and with Hashing you'll not be able to revert from the end result to the original value.
I think you should use git pull --rebase
when collaborating with others on the same branch. You are in your work ? commit ? work ? commit cycle, and when you decide to push your work your push is rejected, because there's been parallel work on the same branch. At this point I always do a pull --rebase
. I do not use squash (to flatten commits), but I rebase to avoid the extra merge commits.
As your Git knowledge increases you find yourself looking a lot more at history than with any other version control systems I've used. If you have a ton of small merge commits, it's easy to lose focus of the bigger picture that's happening in your history.
This is actually the only time I do rebasing(*), and the rest of my workflow is merge based. But as long as your most frequent committers do this, history looks a whole lot better in the end.
(*)
While teaching a Git course, I had a student arrest me on this, since I also advocated rebasing feature branches in certain circumstances. And he had read this answer ;) Such rebasing is also possible, but it always has to be according to a pre-arranged/agreed system, and as such should not "always" be applied. And at that time I usually don't do pull --rebase
either, which is what the question is about ;)
Rows("2:2").Select
ActiveWindow.FreezePanes = True
Select a different range for a different effect, much the same way you would do manually. The "Freeze Top Row" really just is a shortcut new in Excel 2007 (and up), it contains no added functionality compared to earlier versions of Excel.
The only library that I got to work for Chrome, Firefox and MS Edge was rasterizeHTML. It outputs better quality that HTML2Canvas and is still supported unlike HTML2Canvas.
Getting Element and Downloading as PNG
var node= document.getElementById("elementId");
var canvas = document.createElement("canvas");
canvas.height = node.offsetHeight;
canvas.width = node.offsetWidth;
var name = "test.png"
rasterizeHTML.drawHTML(node.outerHTML, canvas)
.then(function (renderResult) {
if (navigator.msSaveBlob) {
window.navigator.msSaveBlob(canvas.msToBlob(), name);
} else {
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = canvas.toDataURL();
a.download = name;
a.click();
document.body.removeChild(a);
}
});
Uses a "standard" set of character orderings (a,b,c, ... etc.). This is in contrast to some specific locales, which may sort characters in different orders ('a-with-acute' may be before or after 'a', depending on the locale, and so on).
On the other hand, looks purely at the values of the raw byte(s) that represent the character.
There's a great sample at http://msdn.microsoft.com/en-us/library/e6883c06.aspx that shows the results of the various StringComparison values. All the way at the end, it shows (excerpted):
StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
You can see that where InvariantCulture yields (U+0069, U+0049, U+00131), Ordinal yields (U+0049, U+0069, U+00131).
A telephone chain is implemented directly as a linked list. Here's how it works:
A group organizer collects the phone numbers of all members.
The organizer assigns each member the number of one other member to call. (Sometimes they will assign their own number so that they know the message got through, but this is optional.)
When a message needs to be sent, the organizer calls the head of the list and delivers the message.
The head calls the number they were assigned and delivers the message.
Step 4 is repeated until everyone has heard the message.
Obviously care must be taken to set up the list in step 2 so that everyone is linked. Also, the list is usually public so that if someone gets an answering machine or busy tone, they can call the next number down and keep the chain moving.
One could think that xlsb has only advantages over xlsm. The fact that xlsm is XML-based and xlsb is binary is that when workbook corruption occurs, you have better chances to repair a xlsm than a xlsb.
They call it a multi-root workspace, and with that you can do debugging easily because:
"With multi-root workspaces, Visual Studio Code searches across all folders for launch.json debug configuration files and displays them with the folder name as a suffix."
Say you have a server and a client folder inside your application folder. If you want to debug them together, without a workspace you have to start two Visual Studio Code instances, one for server, one for client and you need to switch back and forth.
But right now (1.24) you can't add a single file to a workspace, only folders, which is a little bit inconvenient.
Loki's answer points to the Hibernate 3 docs and provides good information, but I was still not getting the results I expected.
Much thrashing, waving of arms and general dead mouse runs finally landed me my cheese.
Because Hibernate 3 is using Simple Logging Facade for Java (SLF4J) (per the docs), if you are relying on Log4j 1.2 you will also need the slf4j-log4j12-1.5.10.jar if you are wanting to fully configure Hibernate logging with a log4j configuration file. Hope this helps the next guy.
Postgres has a very rich system catalog exposed via SQL tables. PG's statistics collector is a subsystem that supports collection and reporting of information about server activity.
Now to figure out the blocking PIDs you can simply query pg_stat_activity
.
select pg_blocking_pids(pid) as blocked_by
from pg_stat_activity
where cardinality(pg_blocking_pids(pid)) > 0;
To, get the query corresponding to the blocking PID, you can self-join or use it as a where clause in a subquery.
SELECT query
FROM pg_stat_activity
WHERE pid IN (select unnest(pg_blocking_pids(pid)) as blocked_by from pg_stat_activity where cardinality(pg_blocking_pids(pid)) > 0);
Note: Since pg_blocking_pids(pid)
returns an Integer[], so you need to unnest
it before you use it in a WHERE pid IN
clause.
Hunting for slow queries can be tedious sometimes, so have patience. Happy hunting.
primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}
I simplified the test a bit - if all(x%y
instead of if not any(not x%y
I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.
pairs = {(x, x+2) for x in primes if x+2 in primes}
Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.
If you have multiple tooltip configurations that you want to initialise, this works well for me.
$("body").tooltip({
selector: '[data-toggle="tooltip"]'
});
You can then set the property on individual elements using data
attributes.
Here are some tidyverse
and custom function options that might work depending on your needs:
library(tidyverse)
# custom function to generate, filter, and mutate the data:
combine_dfs <- function(i){
data_frame(x = rnorm(5), y = runif(5)) %>%
filter(x < y) %>%
mutate(x_plus_y = x + y) %>%
mutate(i = i)
}
df <- 1:5 %>% map_df(~combine_dfs(.))
df <- map_df(1:5, ~combine_dfs(.)) # both give the same results
> df %>% head()
# A tibble: 6 x 4
x y x_plus_y i
<dbl> <dbl> <dbl> <int>
1 -0.973 0.673 -0.300 1
2 -0.553 0.0463 -0.507 1
3 0.250 0.716 0.967 2
4 -0.745 0.0640 -0.681 2
5 -0.736 0.228 -0.508 2
6 -0.365 0.496 0.131 3
You could do something similar if you had a directory of files that needed to be combined:
dir_path <- '/path/to/data/test_directory/'
list.files(dir_path)
combine_files <- function(path, file){
read_csv(paste0(path, file)) %>%
filter(a < b) %>%
mutate(a_plus_b = a + b) %>%
mutate(file_name = file)
}
df <- list.files(dir_path, '\\.csv$') %>%
map_df(~combine_files(dir_path, .))
# or if you have Excel files, using the readxl package:
combine_xl_files <- function(path, file){
readxl::read_xlsx(paste0(path, file)) %>%
filter(a < b) %>%
mutate(a_plus_b = a + b) %>%
mutate(file_name = file)
}
df <- list.files(dir_path, '\\.xlsx$') %>%
map_df(~combine_xl_files(dir_path, .))
Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:
SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;
So we have a table called Jokes with columns JScore and JDate.