I found this to work best
var data = [
{ label: "Choice 1", value: "choice_1" },
{ label: "Choice 2", value: "choice_2" },
{ label: "Choice 3", value: "choice_3" }
];
$("#example")
.autocomplete({
source: data,
minLength: 0
})
.focus(function() {
$(this).autocomplete('search', $(this).val())
});
It searches the labels and places the value into the element $(#example)
If you have simple dropdown like:
<select name="status" id="status">
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
Then you can use this code for getting value:
$(function(){
$("#status").change(function(){
var status = this.value;
alert(status);
if(status=="1")
$("#icon_class, #background_class").hide();// hide multiple sections
});
});
One can make calls by using Bootstrap. The current version does not has any source update issues Trouble updating Bootstrap's typeahead data-source with post response , i.e. the source of bootstrap once updated can be again modified.
Please refer to below for an example:
jQuery('#help').typeahead({
source : function(query, process) {
jQuery.ajax({
url : "urltobefetched",
type : 'GET',
data : {
"query" : query
},
dataType : 'json',
success : function(json) {
process(json);
}
});
},
minLength : 1,
});
I found the following css in order to style a Bootstrap input for a jquery autocomplete:
https://gist.github.com/daz/2168334#file-style-scss
.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
_width: 160px;
padding: 4px 0;
margin: 2px 0 0 0;
list-style: none;
background-color: #ffffff;
border-color: #ccc;
border-color: rgba(0, 0, 0, 0.2);
border-style: solid;
border-width: 1px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
*border-right-width: 2px;
*border-bottom-width: 2px;
}
.ui-menu-item > a.ui-corner-all {
display: block;
padding: 3px 15px;
clear: both;
font-weight: normal;
line-height: 18px;
color: #555555;
white-space: nowrap;
}
.ui-state-hover, &.ui-state-active {
color: #ffffff;
text-decoration: none;
background-color: #0088cc;
border-radius: 0px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
background-image: none;
}
This was my final... It gets around all the type issues also:
Here is a simple textbox that requires a number:
public Sub textbox_memorytotal_TextChanged(sender As Object, e As EventArgs) Handles textbox_memorytotal.TextChanged
TextboxOnlyNumbers(sender)
End Sub
and here is the procedure that corrects all bad input:
Public Sub TextboxOnlyNumbers(ByRef objTxtBox As TextBox)
' ONLY allow numbers
If Not IsNumeric(objTxtBox.Text) Then
' Don't process things like too many backspaces
If objTxtBox.Text.Length > 0 Then
MsgBox("Numerical Values only!")
Try
' If something bad was entered delete the last character
objTxtBox.Text = objTxtBox.Text.Substring(0, objTxtBox.Text.Length - 1)
' Put the cursor and the END of the corrected number
objTxtBox.Select(objTxtBox.Text.Length + 1, 1)
Catch ex As Exception
End Try
End If
End If
End Sub
Installing Ruby gems on a Mac is a common source of confusion and frustration. Unfortunately, most solutions are incomplete, outdated, and provide bad advice. I'm glad the accepted answer here says to NOT use sudo
, which you should never need to do, especially if you don't understand what it does. While I used RVM years ago, I would recommend chruby
in 2020.
Some of the other answers here provide alternative options for installing gems, but they don't mention the limitations of those solutions. What's missing is an explanation and comparison of the various options and why you might choose one over the other. I've attempted to cover most common scenarios in my definitive guide to installing Ruby gems on a Mac.
Also you can use f-string formatting to write integer to file
For appending use following code, for writing once replace 'a' with 'w'.
for i in s_list:
with open('path_to_file','a') as file:
file.write(f'{i}\n')
file.close()
create procedure <procedure_name>(p_cur out sys_refcursor) as begin open p_cur for select * from <table_name> end;
It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for Windows Forms (GUI's) as that uses Win32 for its drawing, which is implemented as STA. If you are using something that's STA model from multiple threads then you get corrupted objects.
This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).
Basically don't worry about it, just accept that Windows GUI threads must be marked as STA otherwise weird stuff happens.
(updated on 3-29-2019 to use the https instead of ssh, so you don't need to use ssh keys)
It seems like for BitBucket, you do have to create a repo online first. Using the instructions from Atlassian, simply create a new BitBucket repository, copy the repository url to the clipboard, and then add that repository as a new remote to your local repository (full steps below):
Get Repo URL
git clone <repository url>
Add Remote Using CLI
cd /path/to/my/repo
git remote add origin https://bitbucket.org/<username>/<reponame>.git
git push -u origin --all
Add Remote Using SourceTree
https://bitbucket.org/<username>/<reponame>.git
)(this method is if you use the ssh url instead of the https url, which looks like ssh://[email protected]/<username>/<reponame>.git
. I recommend just using https)
BitBucket is great for private repos, but you'll need to set up an ssh key to authorize your computer to work with your BitBucket account. Luckily Sourcetree makes it relatively simple:
Creating a Key In SourceTree:
Tools
>Options
, make sure SSH Client:
is set to PuTTY/Plink
under the General
tabTools
>Create or Import SSH Keys
Generate
and move your mouse around to give randomness to the key generatorYou should get something like whats shown in the screenshot below. Copy the public key (highlighted in blue) to your clipboard
Save private Key
and Save public key
to save your keys to wherever you choose (e.g. to <Home Dir>/putty/ssk-key.ppk
and <Home Dir>/putty/ssh-key.pub
respectively) before moving on to the next sectionRegistering The Key In BitBucket
Settings
SSH Keys
tab on the left sidebarAdd SSH Key
, give it a name, and paste the public key you copied in step 4 of the previous sectionThat's it! You should now be able to push/pull to your BitBucket private repos. Your keys aren't just for Git either, many services use ssh keys to identify users, and the best part is you only need one. If you ever lose your keys (e.g. when changing computers), just follow the steps to create and register a new one.
Sidenote: Creating SSH Keys using CLI
Since we are doing this one to death - you don't have to specify a year:
select * from demo
where somedate between to_date('01/01 00:00:00', 'DD/MM HH24:MI:SS')
and to_date('31/12 23:59:59', 'DD/MM HH24:MI:SS');
However the accepted answer by FerranB makes more sense if you want to specify all date values that fall within the current year.
Just use the table name:
SELECT myTable.*, otherTable.foo, otherTable.bar...
That would select all columns from myTable
and columns foo
and bar
from otherTable
.
Generally, you'd use Service Broker
That is trigger -> queue -> application(s)
Edit, after seeing other answers:
FYI: "Query Notifications" is built on Service broker
Edit2:
More links
There is a pretty way to achieve this using Java 8:
List<String> list = Arrays.asList(array);
String joinedString = String.join(",", list);
One more option for disabling the cache is provided by my 3rd Chrome extension Page Size Inspector that disables the cache exactly the same way as Devtools does.
In addition, the extension quickly reports page size, cache usage, network requests and load time of a web page in a convenient way. Plus its open source at Github.
reinterpret_cast
cannot be used for this conversion, the code will not compile. According to C++03 standard section 5.2.10-1:
Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
This conversion is not listed in that section. Even this is invalid:
long l = reinterpret_cast<long>(i)
static_cast
is the one which has to be used here. See this and this SO questions.
Arrays must be assigned a length. To allow for any number of elements, use the List
class.
For example:
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
Check out the Magick++ API to ImageMagick.
You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.
// main.cpp
#include "second.h"
int main () {
secondFunction();
}
// second.h
void secondFunction();
// second.cpp
#include "second.h"
void secondFunction() {
// do stuff
}
When using bootstrap 4 or 5, flexbox could be used to achieve desired effect:
<body class="d-flex flex-column min-vh-100">
<header>HEADER</header>
<content>CONTENT</content>
<footer class="mt-auto"></footer>
</body>
Please check the examples: Bootstrap 4 Bootstrap 5
In bootstrap 3 and without use of bootstrap. The simplest and cross browser solution for this problem is to set a minimal height for body
object. And then set absolute
position for the footer with bottom: 0
rule.
body {
min-height: 100vh;
position: relative;
margin: 0;
padding-bottom: 100px; //height of the footer
box-sizing: border-box;
}
footer {
position: absolute;
bottom: 0;
height: 100px;
}
Please check this example: Bootstrap 3
If you are using Netbeans, there is a nice shortcut to this.
Just define a goal exec:java
and add the property jpda.listen=maven
Tested on Netbeans 7.3
SELECT UPPER(firstname) FROM Person
SELECT LOWER(firstname) FROM Person
It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.
The literal answer is:
return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);
Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:
return (value == 1
? Periods.VariablePeriods
: (value == 2
? Periods.FixedPeriods
: Periods.Unknown));
If you add more values an inline if will become unreadable and a switch would be preferred:
switch (value)
{
case 1:
return Periods.VariablePeriods;
case 2:
return Periods.FixedPeriods;
}
The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.
I think library is a set of utilities to reach a goal (for example, sockets, cryptography, etc). Framework is library + RUNTIME EINVIRONNEMENT. For example, ASP.NET is a framework: it accepts HTTP requests, create page object, invoke lyfe cicle events, etc. Framework does all this, you write a bit of code which will be run at a specific time of the life cycle of current request!
Anyway, very interestering question!
Here's an alternative method that uses only the numpy package. It takes advantage of numpy's array functions, so may be faster when interpolating/extrapolating large arrays:
import numpy as np
def extrap(x, xp, yp):
"""np.interp function with linear extrapolation"""
y = np.interp(x, xp, yp)
y = np.where(x<xp[0], yp[0]+(x-xp[0])*(yp[0]-yp[1])/(xp[0]-xp[1]), y)
y = np.where(x>xp[-1], yp[-1]+(x-xp[-1])*(yp[-1]-yp[-2])/(xp[-1]-xp[-2]), y)
return y
x = np.arange(0,10)
y = np.exp(-x/3.0)
xtest = np.array((8.5,9.5))
print np.exp(-xtest/3.0)
print np.interp(xtest, x, y)
print extrap(xtest, x, y)
Edit: Mark Mikofski's suggested modification of the "extrap" function:
def extrap(x, xp, yp):
"""np.interp function with linear extrapolation"""
y = np.interp(x, xp, yp)
y[x < xp[0]] = yp[0] + (x[x<xp[0]]-xp[0]) * (yp[0]-yp[1]) / (xp[0]-xp[1])
y[x > xp[-1]]= yp[-1] + (x[x>xp[-1]]-xp[-1])*(yp[-1]-yp[-2])/(xp[-1]-xp[-2])
return y
I think you hit the same issue as discussed in this post. You forgot to escape your \
character.
For get response in JSON format :
1.$response = (string) $res->getBody();
$response =json_decode($response); // Using this you can access any key like below
$key_value = $response->key_name; //access key
2. $response = json_decode($res->getBody(),true);
$key_value = $response['key_name'];//access key
Here is a solution in plain and simple C++ code with no fancy function, use DMA to allocate a dynamic string array, and put data in array till you find a open space. please refer code below with comments. I hope it helps.
#include<bits/stdc++.h>
using namespace std;
int main()
{
string data="hello there how are you"; // a_size=5, char count =23
//getline(cin,data);
int count=0; // initialize a count to count total number of spaces in string.
int len=data.length();
for (int i = 0; i < (int)data.length(); ++i)
{
if(data[i]==' ')
{
++count;
}
}
//declare a string array +1 greater than the size
// num of space in string.
string* str = new string[count+1];
int i, start=0;
for (int index=0; index<count+1; ++index) // index array to increment index of string array and feed data.
{ string temp="";
for ( i = start; i <len; ++i)
{
if(data[i]!=' ') //increment temp stored word till you find a space.
{
temp=temp+data[i];
}else{
start=i+1; // increment i counter to next to the space
break;
}
}str[index]=temp;
}
//print data
for (int i = 0; i < count+1; ++i)
{
cout<<str[i]<<" ";
}
return 0;
}
SET string=bath Abath Bbath XYZbathABC
SET modified=%string:bath=hello%
ECHO %string%
ECHO %modified%
EDIT
Didn't see at first that you wanted the replacement to be preceded by reading the string from a file.
Well, with a batch file you don't have much facility of working on files. In this particular case, you'd have to read a line, perform the replacement, then output the modified line, and then... What then? If you need to replace all the ocurrences of 'bath' in all the file, then you'll have to use a loop:
@ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
FOR /F %%L IN (file.txt) DO (
SET "line=%%L"
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO !line:bath=hello!
ENDLOCAL
)
ENDLOCAL
You can add a redirection to a file:
ECHO !line:bath=hello!>>file2.txt
Or you can apply the redirection to the batch file. It must be a different file.
EDIT 2
Added proper toggling of delayed expansion for correct processing of some characters that have special meaning with batch script syntax, like !
, ^
et al. (Thanks, jeb!)
I would use Prototype's update
method which supports plain text, an HTML snippet or any JavaScript object that defines a toString
method.
$("field_name").update("New text");
Ed: phpMyAdmin is for MySQL, but the asker needs something for Microsoft SQL Server.
Most solutions that I found involve using an ODBC Driver and then whatever client application you use. For example, Gorilla SQL claims to be able to do that, even though the project seems abandoned.
Most good solutions are either using Remote Desktop or VMware/Parallels.
When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.
You can see more on Qt Documentation
In TypeScript or using Babel, you can import json file in your code.
// Babel
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'
Reference: https://hackernoon.com/import-json-into-typescript-8d465beded79
The cunningly-named urlencode() and urldecode().
However, you shouldn't need to use urldecode()
on variables that appear in $_POST
and $_GET
.
The keyword for Oracle PL/SQL is "ELSIF" ( no extra "E"), not ELSEIF (yes, confusing and stupid)
declare
var_number number;
begin
var_number := 10;
if var_number > 100 then
dbms_output.put_line(var_number||' is greater than 100');
elsif var_number < 100 then
dbms_output.put_line(var_number||' is less than 100');
else
dbms_output.put_line(var_number||' is equal to 100');
end if;
end;
I used this code and it works just fine
const int margin = 5;
Rectangle rect = new Rectangle(
Screen.PrimaryScreen.WorkingArea.X + margin,
Screen.PrimaryScreen.WorkingArea.Y + margin,
Screen.PrimaryScreen.WorkingArea.Width - 2 * margin,
Screen.PrimaryScreen.WorkingArea.Height - 2 * (margin - 7));
this.Bounds = rect;
should be
matchFound = (expiryDate - DateTime.Now).TotalDays < 30;
note the total days otherwise you'll get werid behaviour
I am not sure did you see this list of MS SQL Modules for Node JS
Share your experience after using one if possible .
Good Luck
use 'any'
dict = {}
if any(dict) :
# true
# dictionary is not empty
else :
# false
# dictionary is empty
Use operator overloading feature of java
class Test {
void printType(String x) {
System.out.print("String");
}
void printType(int x) {
System.out.print("Int");
}
// same goes on with boolean,double,float,object ...
}
Alternatively, if your objective is to output directly to a file or stdout, you can use cat
:
cat(s1, s2, sep=", ")
<div ng-bind-html="myText"></div>
No need to put into html {{}} interpolation tags like you did {{myText}}.
and don't forget to use ngSanitize in module like e.g.
var app = angular.module("myApp", ['ngSanitize']);
and add its cdn dependency in index.html page https://cdnjs.com/libraries/angular-sanitize
simplest thing to do; just add:
app:navigationIcon="@drawable/ic_action_navigation_menu">
to the <android.support.v7.widget.Toolbar
tag
where @drawable/ic_action_navigation_menu
is the name of icon
The correct answer is to use Environment.NewLine
, as you've noted. It is environment specific and provides clarity over "\r\n" (but in reality makes no difference).
foreach (var item in FirmNameList)
{
if (FirmNames != "")
{
FirmNames += ", " + Environment.NewLine;
}
FirmNames += item;
}
If you want to check for local files first do:
@font-face {
font-family: 'Green Sans Web';
src:
local('Green Web'),
local('GreenWeb-Regular'),
url('GreenWeb.ttf');
}
There is a more elaborate description of what to do here.
The only way I'm aware of is the trick used by FileSaver.js:
<a>
tag.href
attribute to the blob's URL.download
attribute to the filename. <a>
tag.Here is a simplified example (jsfiddle):
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
I wrote this example just to illustrate the idea, in production code use FileSaver.js instead.
Notes
You can also use batch functions for this:
@echo off
setlocal
goto MAIN
::-----------------------------------------------
:: "%~f2" get abs path of %~2.
::"%~fs2" get abs path with short names of %~2.
:setAbsPath
setlocal
set __absPath=%~f2
endlocal && set %1=%__absPath%
goto :eof
::-----------------------------------------------
:MAIN
call :setAbsPath ABS_PATH ..\
echo %ABS_PATH%
endlocal
Turns out the problem was the main image that we used on our app at the time. The actual size of the image was too large, so we compressed it. Then it worked like a charm, no loss in quality and the app ran fine on the emulator.
Here's an alternative since you don't like the cast to int:
foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))
Console.Write(b.ToString());
You can do this easily with the KoGrid plugin for KnockoutJS.
<script type="text/javascript">
$(function () {
window.viewModel = {
myObsArray: ko.observableArray([
{ id: 1, firstName: 'John', lastName: 'Doe', createdOn: '1/1/2012', birthday: '1/1/1977', salary: 40000 },
{ id: 1, firstName: 'Jane', lastName: 'Harper', createdOn: '1/2/2012', birthday: '2/1/1976', salary: 45000 },
{ id: 1, firstName: 'Jim', lastName: 'Carrey', createdOn: '1/3/2012', birthday: '3/1/1985', salary: 60000 },
{ id: 1, firstName: 'Joe', lastName: 'DiMaggio', createdOn: '1/4/2012', birthday: '4/1/1991', salary: 70000 }
])
};
ko.applyBindings(viewModel);
});
</script>
<div data-bind="koGrid: { data: myObsArray }">
Comparator<Long> comparator = Collections.reverseOrder();
Collections.sort(arrayList, comparator);
Another one is OxyPlot, which is an open-source cross-platform (WPF, Silverlight, WinForms, Mono) .Net plotting library.
If you have a SOCK_STREAM
socket, recv
just gets "up to the first 3000 bytes" from the stream. There is no clear guidance on how big to make the buffer: the only time you know how big a stream is, is when it's all done;-).
If you have a SOCK_DGRAM
socket, and the datagram is larger than the buffer, recv
fills the buffer with the first part of the datagram, returns -1, and sets errno to EMSGSIZE. Unfortunately, if the protocol is UDP, this means the rest of the datagram is lost -- part of why UDP is called an unreliable protocol (I know that there are reliable datagram protocols but they aren't very popular -- I couldn't name one in the TCP/IP family, despite knowing the latter pretty well;-).
To grow a buffer dynamically, allocate it initially with malloc
and use realloc
as needed. But that won't help you with recv
from a UDP source, alas.
Use:
vector<vector<float>> vecArray; //both dimensions are open!
.SILENT:
Type " .SILENT: " in the beginning of your script without colons.
With delay and fade :
setTimeout(function(){
$(".alert").each(function(index){
$(this).delay(200*index).fadeTo(1500,0).slideUp(500,function(){
$(this).remove();
});
});
},2000);
Use li:before
with an escaped Hex HTML Entity (or any plain text).
Example
My example will produce lists with check marks as bullets.
CSS:
ul {
list-style: none;
padding: 0px;
}
ul li:before
{
content: '\2713';
margin: 0 1em; /* any design */
}
Browser Compatibility
Haven't tested myself, but it should be supported as of IE8. At least that's what quirksmode & css-tricks say.
You can use conditional comments to apply older/slower solutions like images, or scripts. Better yet, use both with <noscript>
for the images.
HTML:
<!--[if lt IE 8]>
*SCRIPT SOLUTION*
<noscript>
*IMAGE SOLUTION*
</noscript>
<![endif]-->
About background images
Background images are indeed easy to handle, but...
background-size
is actually only as of IE9.list-style
(the more logical choice) easier.Enjoy.
$ alias gpuom='git push origin master'
$ alias
hit Enter.$ vim ~/.bashrc
and hit Enter (I'm guessing you are familiar with vim).#My custom aliases
alias gpuom='git push origin master'
alias gplom='git pull origin master'
$ alias
hit Enter.Check your XML
files for resolving the Errors.Most of the time the changes made to your XML
files get Affected.so try to check the last changes you made.
Try to Clean your Project....It Works
Happy Coding:)
git rm --cached file
should do what you want.
You can read more details at git help rm
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
I think in your case you don't really need a groupby. I would sort by descending order your B column, then drop duplicates at column A and if you want you can also have a new nice and clean index like that:
df.sort_values('B', ascending=False).drop_duplicates('A').sort_index().reset_index(drop=True)
There are scripts on CPAN which attempt to uninstall modules:
ExtUtils::Packlist shows sample module removing code, modrm
.
I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.
Try creating scriptfile as a separate command:
Command myCommand = new Command(scriptfile);
then you can add parameters with
CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);
and finally
pipeline.Commands.Add(myCommand);
Here is the complete, edited code:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command(scriptfile);
CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
// Execute PowerShell script
results = pipeline.Invoke();
I know this post is old, sorry for that.
You can also type 10x
for cols and x2
for rows, if you want to have only one attribute.
[textarea* your-message x3 class:form-control] <!-- only rows -->
[textarea* your-message 10x class:form-control] <!-- only columns -->
[textarea* your-message 10x3 class:form-control] <!-- both -->
in laragon delete all internal data files from "C:\laragon\data\mysql" and restart it, that worked for me
%timeit
is an ipython magic function, which can be used to time a particular piece of code (A single execution statement, or a single method).
From the docs:
%timeit
Time execution of a Python statement or expression Usage, in line mode: %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
To use it, for example if we want to find out whether using xrange
is any faster than using range
, you can simply do:
In [1]: %timeit for _ in range(1000): True
10000 loops, best of 3: 37.8 µs per loop
In [2]: %timeit for _ in xrange(1000): True
10000 loops, best of 3: 29.6 µs per loop
And you will get the timings for them.
The major advantage of %timeit
are:
that you don't have to import timeit.timeit
from the standard library, and run the code multiple times to figure out which is the better approach.
%timeit will automatically calculate number of runs required for your code based on a total of 2 seconds execution window.
You can also make use of current console variables without passing the whole code snippet as in case of timeit.timeit
to built the variable that is built in an another environment that timeit works.
Use : $window.location.href = '/Home.html';
The following implementation uses the Fisher-Yates algorithm AKA the Knuth Shuffle. It runs in O(n) time and shuffles in place, so is better performing than the 'sort by random' technique, although it is more lines of code. See here for some comparative performance measurements. I have used System.Random, which is fine for non-cryptographic purposes.*
static class RandomExtensions
{
public static void Shuffle<T> (this Random rng, T[] array)
{
int n = array.Length;
while (n > 1)
{
int k = rng.Next(n--);
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
}
Usage:
var array = new int[] {1, 2, 3, 4};
var rng = new Random();
rng.Shuffle(array);
rng.Shuffle(array); // different order from first call to Shuffle
* For longer arrays, in order to make the (extremely large) number of permutations equally probable it would be necessary to run a pseudo-random number generator (PRNG) through many iterations for each swap to produce enough entropy. For a 500-element array only a very small fraction of the possible 500! permutations will be possible to obtain using a PRNG. Nevertheless, the Fisher-Yates algorithm is unbiased and therefore the shuffle will be as good as the RNG you use.
You can't make the user's mouse do anything. But you have full control over what happens when an event triggers.
What you can do is do a click on body load. W3Schools has an example here.
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
Assuming your dataObject is defined the way you specified, you do this:
var dataArray = [];
for (var key in dataObject)
dataArray.push(dataObject[key]);
And end up having dataArray populated with inner objects.
In the most shared hosts you can't set it.
On a VPS or dedicated server, you can set it, but everything has its price.
On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)
If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.
If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.
You can also add
<Resource
auth="Container"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
maxActive="20"
maxIdle="10"
maxWait="-1"
name="ds/flexeraDS"
type="javax.sql.DataSource"
url="jdbc:derby:flexeraDB;create=true"
/>
under META-INF/context.xml
file (This will be only at application level).
Or
help(list.append)
if you're generally poking around.
In order to pass the parameters you create new intent and put a parameter map:
Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);
In order to get the parameters values inside the started activity, you must call the get[type]Extra()
on the same intent:
// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"
If your parameters are ints you would use getIntExtra()
instead etc.
Now you can use your parameters like you normally would.
A few years ago I wrote a winforms app with the help of a few win32 api's to completely lock myself out of my computer for an hour so that it would force me to go and exercise. Because I was lazy? No... because I had a personal fitness goal. Sometimes you just need a little kick to get started :)
In my case, we have time series from different devices but some devices could not send any value during some period. So we should create NA values for every device and time period and after that do fillna.
df = pd.DataFrame([["device1", 1, 'first val of device1'], ["device2", 2, 'first val of device2'], ["device3", 3, 'first val of device3']])
df.pivot(index=1, columns=0, values=2).fillna(method='ffill').unstack().reset_index(name='value')
Result:
0 1 value
0 device1 1 first val of device1
1 device1 2 first val of device1
2 device1 3 first val of device1
3 device2 1 None
4 device2 2 first val of device2
5 device2 3 first val of device2
6 device3 1 None
7 device3 2 None
8 device3 3 first val of device3
I would check to see if the SqlDataReader has rows returned first:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
{
...
}
brew install python3
create alias in your shell profile
alias pip3="python3 -m pip"
in my .zshrc
? ~ pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)
<?php
if ( session_id() != "" ) {
session_start();
}
Basically, you need to check if a session was started before creating another one; ... more reading.
On the other hand, you chose to destroy an existing session before creating another one using session_destroy()
.
At least some versions of SQL (Oracle, Informix, DB2, ISO Standard) support:
WHERE MOD(value, 2) = 1
MySQL supports '%' as the modulus operator:
WHERE value % 2 = 1
Hmmm...
As Darin said, you can specify a higher connection timeout value, but I doubt that's really the issue.
When you get connection timeouts, it's typically a problem with one of the following:
Network configuration - slow connection between your web server/dev box and the SQL server. Increasing the timeout may correct this, but it'd be wise to investigate the underlying problem.
Connection string. I've seen issues where an incorrect username/password will, for some reason, give a timeout error instead of a real error indicating "access denied." This shouldn't happen, but such is life.
Connection String 2: If you're specifying the name of the server incorrectly, or incompletely (for instance, mysqlserver
instead of mysqlserver.webdomain.com
), you'll get a timeout. Can you ping the server using the server name exactly as specified in the connection string from the command line?
Connection string 3 : If the server name is in your DNS (or hosts file), but the pointing to an incorrect or inaccessible IP, you'll get a timeout rather than a machine-not-found-ish error.
The query you're calling is timing out. It can look like the connection to the server is the problem, but, depending on how your app is structured, you could be making it all the way to the stage where your query is executing before the timeout occurs.
Connection leaks. How many processes are running? How many open connections? I'm not sure if raw ADO.NET performs connection pooling, automatically closes connections when necessary ala Enterprise Library, or where all that is configured. This is probably a red herring. When working with WCF and web services, though, I've had issues with unclosed connections causing timeouts and other unpredictable behavior.
Things to try:
Do you get a timeout when connecting to the server with SQL Management Studio? If so, network config is likely the problem. If you do not see a problem when connecting with Management Studio, the problem will be in your app, not with the server.
Run SQL Profiler, and see what's actually going across the wire. You should be able to tell if you're really connecting, or if a query is the problem.
Run your query in Management Studio, and see how long it takes.
Good luck!
//package.json
"scripts": {
"postbuildNamingScript": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./powerShellPostBuildScript.ps1",
// powerShellPostBuildScript.ps1
move build/static/js build/new-folder-name
(Get-Content build/index.html).replace('static/js', 'new-folder-name') | Set-Content
build/index.html
"Finished Running BuildScript"
Running npm run postbuildNamingScript
in powershell will move the JS files to build/new-folder-name
and point to the new location from index.html
.
This can be solved with an assignment tag:
from django import template
register = template.Library()
@register.assignment_tag
def query(qs, **kwargs):
""" template tag which allows queryset filtering. Usage:
{% query books author=author as mybooks %}
{% for book in mybooks %}
...
{% endfor %}
"""
return qs.filter(**kwargs)
Use the following code:
//for Internet Explorer
document.getElementById("FirstDiv").removeNode(true);
//for other browsers
var fDiv = document.getElementById("FirstDiv");
fDiv.removeChild(fDiv.childNodes[0]); //first check on which node your required node exists, if it is on [0] use this, otherwise use where it exists.
If you want to set cookie and get it outside of request, Laravel is not your friend.
Laravel cookies are part of Request, so if you want to do this outside of Request object, use good 'ole PHP setcookie(..) and $_COOKIE to get it.
To get the index
values as a list
/list
of tuple
s for Index
/MultiIndex
do:
df.index.values.tolist() # an ndarray method, you probably shouldn't depend on this
or
list(df.index.values) # this will always work in pandas
All you need to do is just use Google as a Proxy server.
https://www.google.ie/gwt/x?u=[YourHttpLink].
<iframe src="https://www.google.ie/gwt/x?u=[Your http link]"></frame>
It worked for me.
In this example we are creating a function to bring a comma delineated list of distinct line level AP invoice hold reasons into one field for header level query:
FUNCTION getHoldReasonsByInvoiceId (p_InvoiceId IN NUMBER) RETURN VARCHAR2
IS
v_HoldReasons VARCHAR2 (1000);
v_Count NUMBER := 0;
CURSOR v_HoldsCusror (p2_InvoiceId IN NUMBER)
IS
SELECT DISTINCT hold_reason
FROM ap.AP_HOLDS_ALL APH
WHERE status_flag NOT IN ('R') AND invoice_id = p2_InvoiceId;
BEGIN
v_HoldReasons := ' ';
FOR rHR IN v_HoldsCusror (p_InvoiceId)
LOOP
v_Count := v_COunt + 1;
IF (v_Count = 1)
THEN
v_HoldReasons := rHR.hold_reason;
ELSE
v_HoldReasons := v_HoldReasons || ', ' || rHR.hold_reason;
END IF;
END LOOP;
RETURN v_HoldReasons;
END;
Sub DeleteEmptyRows()
Worksheets("YourSheetName").Activate
On Error Resume Next
Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.
EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.
I've found FileFormat.info's Unicode Character Search to be most helpful in finding exact character codes.
Entering simply '
(the character to the left of the return key on my US Mac keyboard) into their search yields several results of various curls and languages.
I would presume the original question was asking for the typographically correct U+02BC '
, rather than the typewriter fascimile U+0027 '
.
The W3C recommends hex codes for HTML entities (see below). For U+02BC that would be ʼ
, rather than '
for U+0027.
http://www.w3.org/International/questions/qa-escapes
Using character escapes in markup and CSS
Hex vs. decimal. Typically when the Unicode Standard refers to or lists characters it does so using a hexadecimal value. … Given the prevalence of this convention, it is often useful, though not required, to use hexadecimal numeric values in escapes rather than decimal values…
http://www.w3.org/TR/html4/charset.html
5 HTML Document Representation … 5.4 Undisplayable characters
…If missing characters are presented using their numeric representation, use the hexadecimal (not decimal) form, since this is the form used in character set standards.
There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.
create this form element inside your form:
<input type="hidden" name="total" value="">
So your form like this:
<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
<a href="#" onclick="setValue();">Click to submit</a>
</form>
Then your javascript something like this:
<script>
function setValue(){
document.sampleForm.total.value = 100;
document.forms["sampleForm"].submit();
}
</script>
On Rails, one can do the following using the rails console
:
connection = ActiveRecord::Base.connection
connection.execute("SET FOREIGN_KEY_CHECKS=0;")
It's "a reference to the object in the current context" effectively. For example, to print out "this object" you might write:
System.out.println(this);
Note that your usage of "global variable" is somewhat off... if you're using this.variableName
then by definition it's not a global variable - it's a variable specific to this particular instance.
SELECT
CASE
WHEN xyz.something = 1 THEN 'SOMETEXT'
WHEN xyz.somethingelse = 1 THEN 'SOMEOTHERTEXT'
WHEN xyz.somethingelseagain = 2 THEN 'SOMEOTHERTEXTGOESHERE'
ELSE 'SOMETHING UNKNOWN'
END AS ColumnName;
Here is how you do it:
In .h
#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif
extern "C" // Only if you are using C++ rather than C
{
EXPORT int __stdcall add2(int num);
EXPORT int __stdcall mult(int num1, int num2);
}
in .cpp
extern "C" // Only if you are using C++ rather than C
{
EXPORT int __stdcall add2(int num)
{
return num + 2;
}
EXPORT int __stdcall mult(int num1, int num2)
{
int product;
product = num1 * num2;
return product;
}
}
The macro tells your module (i.e your .cpp files) that they are providing the dll stuff to the outside world. People who incude your .h file want to import the same functions, so they sell EXPORT as telling the linker to import. You need to add BUILD_DLL to the project compile options, and you might want to rename it to something obviously specific to your project (in case a dll uses your dll).
You might also need to create a .def file to rename the functions and de-obfuscate the names (C/C++ mangles those names). This blog entry might be an interesting launching off point about that.
Loading your own custom dlls is just like loading system dlls. Just ensure that the DLL is on your system path. C:\windows\ or the working dir of your application are an easy place to put your dll.
WINDOWS
For me solution was not to use
mkvirtualenv
, but:
python -m venv path/to/your/virtualenv
workon works correctly.
while in virtualenv: pip -V
shows virtualenv's path to pip
Is there some command to create this folder?
If smb face this issue again, you should know the most simple way to create .m2
folder.
If you unzipped maven and set up maven path variable - just try mvn clean
command from anywhere you like!
Dont be afraid of error messages when running - it works and creates needed directory.
you can turn the ":" to space, and do the split.eg
>>> f=open("/proc/net/dev")
>>> for line in f:
... line=line.replace(":"," ").split()
... print len(line)
no regex needed (for this case)
If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.
class CallbackTest {
myCallback: Function;
}
If you have other testing applications like SQL web batch etc, uninstall them because they are running in port 3306.
While zolley's answer is perfectly right for the question, here's a more general solution for any range, plus explanation:
=COUNTIF($A$1:$C$50, INDIRECT(ADDRESS(ROW(), COLUMN(), 4))) > 1
Please note that in this example I will be using the range A1:C50
.
The first parameter ($A$1:$C$50
) should be replaced with the range on which you would like to highlight duplicates!
to highlight duplicates:
Format
> Conditional formatting...
Apply to range
, select the range to which the rule should be applied.Format cells if
, select Custom formula is
on the dropdown.Why does it work?
COUNTIF(range, criterion)
, will compare every cell in range
to the criterion
, which is processed similarly to formulas. If no special operators are provided, it will compare every cell in the range with the given cell, and return the number of cells found to be matching the rule (in this case, the comparison). We are using a fixed range (with $
signs) so that we always view the full range.
The second block, INDIRECT(ADDRESS(ROW(), COLUMN(), 4))
, will return current cell's content. If this was placed inside the cell, docs will have cried about circular dependency, but in this case, the formula is evaluated as if it was in the cell, without changing it.
ROW()
and COLUMN()
will return the row number and column number of the given cell respectively. If no parameter is provided, the current cell will be returned (this is 1-based, for example, B3
will return 3 for ROW()
, and 2 for COLUMN()
).
Then we use: ADDRESS(row, column, [absolute_relative_mode])
to translate the numeric row and column to a cell reference (like B3
. Remember, while we are inside the cell's context, we don't know it's address OR content, and we need the content in order to compare with). The third parameter takes care for the formatting, and 4
returns the formatting INDIRECT()
likes.
INDIRECT()
, will take a cell reference and return its content. In this case, the current cell's content. Then back to the start, COUNTIF()
will test every cell in the range against ours, and return the count.
The last step is making our formula return a boolean, by making it a logical expression: COUNTIF(...) > 1
. The > 1
is used because we know there's at least one cell identical to ours. That's our cell, which is in the range, and thus will be compared to itself. So to indicate a duplicate, we need to find 2 or more cells matching ours.
Sources:
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
Here is how you can do it with a socket on php-fpm 7
install socat
apt-get install socat
#!/bin/sh
if echo /dev/null | socat UNIX:/var/run/php/php7.0-fpm.sock - ; then
echo "$home/run/php-fpm.sock connect OK"
else
echo "$home/run/php-fpm.sock connect ERROR"
fi
You can also check if the service is running like this.
service php7.0-fpm status | grep running
It will return
Active: active (running) since Sun 2017-04-09 12:48:09 PDT; 48s ago
The following is equivalent to your second code block:
var f = function () {
//Some logic here...
};
var fr = f;
fr(pars);
If you want to actually pass a reference to a function to some other function, you can do something like this:
function fiz(x, y, z) {
return x + y + z;
}
// elsewhere...
function foo(fn, p, q, r) {
return function () {
return fn(p, q, r);
}
}
// finally...
f = foo(fiz, 1, 2, 3);
f(); // returns 6
You're almost certainly better off using a framework for this sort of thing, though.
Without any deep knowledge of the mySQL engine, I'd say this sounds like a memory saving strategy. I assume the reason is behind this paragraph from the docs:
Each BLOB or TEXT value is represented internally by a separately allocated object. This is in contrast to all other data types, for which storage is allocated once per column when the table is opened.
It seems like pre-filling these column types would lead to memory usage and performance penalties.
References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.
EDIT::
I am thinking of
int &x = y;
as almost equivalent of
int* __px = &y;
#define x (*__px)
where __px
is a fresh name, and the #define x
works only inside the block containing the declaration of x
reference.
Firstly update it. If affected row count = 0 then insert it. Its the easiest and suitable for all RDBMS.
Assuming you are running on a *nix platform, use cron
and the php
executable.
EDIT:
There are quite a number of questions asking for "running php without cron" on SO already. Here's one:
Schedule scripts without using CRON
That said, the exec() answer above sounds very promising :)
import os
os.path.getsize(fullpathhere) > 0
I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).
If you have configured ssh key to connect to your remote server, you could use the following command:
rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/
Where v
option is --verbose
, a
option is --archive
- archive mode, P
option same as --partial
- keep partially transferred files, e
option is --rsh=COMMAND
- specifying the remote shell to use.
Try this:
select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2
The number in the having should match the amount of people. If you also need the Status to be Complete
use this where
clause instead of the previous one:
where personName in ('Ryan', 'Holly') and status = 'Complete'
Another sneaky issue related to this is naming your columns with -
instead of _
.
Something like this will trigger an error at the moment your tables are getting created.
@Column(name="verification-token")
As an addition to user39544
's answer, one more type of syntax for crontab -e
:
@reboot sleep 60 && /usr/local/bin/docker-compose -f /path_to_your_project/docker-compose.yml up -d
Use htmlspecialchars()
:
echo htmlspecialchars($_POST['contact_list']);
You can even improve your form processing by stripping all tags with strip_tags()
and remove all white spaces with trim()
:
function processText($text) {
$text = strip_tags($text);
$text = trim($text);
$text = htmlspecialchars($text);
return $text;
}
echo processText($_POST['contact_list']);
Using:
SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
...will show you the ctn_no
value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:
SELECT t.ctn_no
FROM YOUR_TABLE t
WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
If you want to see the other column values associated with the duplicate, you'll want to use a self join:
SELECT x.*
FROM YOUR_TABLE x
JOIN (SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no
If you're interested in the physical RAM, use the command dmidecode
. It gives you a lot more information than just that, but depending on your use case, you might also want to know if the 8G in the system come from 2x4GB sticks or 4x2GB sticks.
I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.
One can write his own customised ufunc
in C, which surely is more efficient, or by invoking np.frompyfunc
, which is built-in factory method. After testing, this is more efficient than np.vectorize
:
f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)
%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms
I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post
If you are creating a div
and trying to add a title
to it.
Try
var myDiv= document.createElement("div");
myDiv.setAttribute('title','mytitle');
With serialize the data as JSON and Base64, dependency jquery.cookie.js :
var putCookieObj = function(key, value) {
$.cookie(key, btoa(JSON.stringify(value)));
}
var getCookieObj = function (key) {
var cookie = $.cookie(key);
if (typeof cookie === "undefined") return null;
return JSON.parse(atob(cookie));
}
:)
"Just set the MaxSelectionCount
to 1 so that users cannot select more than one day. Then in the SelectionRange.Start.ToString()
. There is nothing available to show the selection of only one day." - Justin Etheredge
From here.
If you're creating 2 executable JAR files, each will have it's own manifest file, and each manifest file will specify the class that contains the main()
method you want to use to start execution.
In each JAR file, the manifest will be a file with the following path / name inside the JAR - META-INF/MANIFEST.MF
There are ways to specify alternatively named files as a JAR's manifest using the JAR command-line parameters.
The specific class you want to use is specified using Main-Class: package.classname inside the META-INF/MANIFEST.MF file.
As for how to do this in Netbeans - not sure off the top of my head - I usually use IntelliJ and / or Eclipse and usually build the JAR through ANT or Maven anyway.
SELECT *
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, date_created) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
You need to check the month and year.
if you are using the fedora distro, you can change the file
/etc/containers/registries.conf
Adding domain docker.io
it should work
example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
example_list = [int(k) for k in example_string.split(',')]
Hi I got this error because I left out the ampersand (&) in
; php.ini
error_reporting = E_ALL & ~E_DEPRECATED
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
I used the below to solve this problem.
import org.apache.commons.lang.StringUtils;
StringUtils.capitalize(MyString);
Thanks to Ted Hopp for rightly pointing out that the question should have been TITLE CASE instead of modified CAMEL CASE.
Camel Case is usually without spaces between words.
I think you are looking for this
String[] car = new String[10];
int size = car.length;
Lazy notes in comments.
#include <stdio.h>
// for malloc
#include <stdlib.h>
// you need the prototype
char *substring(int i,int j,char *ch);
int main(void /* std compliance */)
{
int i=0,j=2;
char s[]="String";
char *test;
// s points to the first char, S
// *s "is" the first char, S
test=substring(i,j,s); // so s only is ok
// if test == NULL, failed, give up
printf("%s",test);
free(test); // you should free it
return 0;
}
char *substring(int i,int j,char *ch)
{
int k=0;
// avoid calc same things several time
int n = j-i+1;
char *ch1;
// you can omit casting - and sizeof(char) := 1
ch1=malloc(n*sizeof(char));
// if (!ch1) error...; return NULL;
// any kind of check missing:
// are i, j ok?
// is n > 0... ch[i] is "inside" the string?...
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return ch1;
}
You will notice a big change when selecting options if you type in "java -version" after doing so. So if you run update-alternatives --config java
and select option 3
, you will be using the Sun implementation.
Also, with regards to auto
vs manual mode
, making a selection should take it out of auto mode
per this page stating:
When using the
--config
option, alternatives will list all of the choices for the link group of which given name is the master link. You will then be prompted for which of the choices to use for the link group. Once you make a change, the link group will no longer be inauto mode
. You will need to use the--auto
option in order to return to the automatic state.
And I believe auto mode
is set when you install the first/only JRE/JDK.
You're supposed to use setImageResource
instead of setBackgroundResource
.
To compare two files in Eclipse, first select them in the Project Explorer / Package Explorer / Navigator with control-click. Now right-click on one of the files, and the following context menu will appear. Select Compare With / Each Other.
declare @d1 datetime, @d2 datetime
select @d1 = '4/19/2017', @d2 = '5/7/2017'
DECLARE @Counter int = datediff(DAY,@d1 ,@d2 )
DECLARE @C int = 0
DECLARE @SUM int = 0
WHILE @Counter > 0
begin
SET @SUM = @SUM + IIF(DATENAME(dw,
DATEADD(day,@c,@d1))IN('Sunday','Monday','Tuesday','Wednesday','Thursday')
,1,0)
SET @Counter = @Counter - 1
set @c = @c +1
end
select @Sum
You can create a boolean field and check it inside run:
public class Task implements Runnable {
private volatile boolean isRunning = true;
public void run() {
while (isRunning) {
//do work
}
}
public void kill() {
isRunning = false;
}
}
To stop it just call
task.kill();
This should work.
If order is important you can create your own events and bind callbacks to fire when those events are triggered by other callbacks.
$('#mydiv').click(function(e) {
// maniplate #mydiv ...
$('#mydiv').trigger('mydiv-manipulated');
});
$('#mydiv').bind('mydiv-manipulated', function(e) {
// do more stuff now that #mydiv has been manipulated
return;
});
Something like that at least.
I've had a go at putting together a multiprocessing example of file text searching. This is my first effort at using the multiprocessing module; and I'm a python n00b. Comments quite welcome. I'll have to wait until at work to test on really big files. It should be faster on multi core systems than single core searching. Bleagh! How do I stop the processes once the text has been found and reliably report line number?
import multiprocessing, os, time
NUMBER_OF_PROCESSES = multiprocessing.cpu_count()
def FindText( host, file_name, text):
file_size = os.stat(file_name ).st_size
m1 = open(file_name, "r")
#work out file size to divide up to farm out line counting
chunk = (file_size / NUMBER_OF_PROCESSES ) + 1
lines = 0
line_found_at = -1
seekStart = chunk * (host)
seekEnd = chunk * (host+1)
if seekEnd > file_size:
seekEnd = file_size
if host > 0:
m1.seek( seekStart )
m1.readline()
line = m1.readline()
while len(line) > 0:
lines += 1
if text in line:
#found the line
line_found_at = lines
break
if m1.tell() > seekEnd or len(line) == 0:
break
line = m1.readline()
m1.close()
return host,lines,line_found_at
# Function run by worker processes
def worker(input, output):
for host,file_name,text in iter(input.get, 'STOP'):
output.put(FindText( host,file_name,text ))
def main(file_name,text):
t_start = time.time()
# Create queues
task_queue = multiprocessing.Queue()
done_queue = multiprocessing.Queue()
#submit file to open and text to find
print 'Starting', NUMBER_OF_PROCESSES, 'searching workers'
for h in range( NUMBER_OF_PROCESSES ):
t = (h,file_name,text)
task_queue.put(t)
#Start worker processes
for _i in range(NUMBER_OF_PROCESSES):
multiprocessing.Process(target=worker, args=(task_queue, done_queue)).start()
# Get and print results
results = {}
for _i in range(NUMBER_OF_PROCESSES):
host,lines,line_found = done_queue.get()
results[host] = (lines,line_found)
# Tell child processes to stop
for _i in range(NUMBER_OF_PROCESSES):
task_queue.put('STOP')
# print "Stopping Process #%s" % i
total_lines = 0
for h in range(NUMBER_OF_PROCESSES):
if results[h][1] > -1:
print text, 'Found at', total_lines + results[h][1], 'in', time.time() - t_start, 'seconds'
break
total_lines += results[h][0]
if __name__ == "__main__":
main( file_name = 'testFile.txt', text = 'IPI1520' )
There is one solution to this problem across all possible inputs. Cheat.
For me, when starting out, the point to these only became clear when you stop looking at them as things to make your code easier/faster to write - this is not their purpose. They have a number of uses:
(This is going to lose the pizza analogy, as it's not very easy to visualise a use of this)
Say you are making a simple game on screen and It will have creatures with which you interact.
A: They can make your code easier to maintain in the future by introducing a loose coupling between your front end and your back end implementation.
You could write this to start with, as there are only going to be trolls:
// This is our back-end implementation of a troll
class Troll
{
void Walk(int distance)
{
//Implementation here
}
}
Front end:
function SpawnCreature()
{
Troll aTroll = new Troll();
aTroll.Walk(1);
}
Two weeks down the line, marketing decide you also need Orcs, as they read about them on twitter, so you would have to do something like:
class Orc
{
void Walk(int distance)
{
//Implementation (orcs are faster than trolls)
}
}
Front end:
void SpawnCreature(creatureType)
{
switch(creatureType)
{
case Orc:
Orc anOrc = new Orc();
anORc.Walk();
case Troll:
Troll aTroll = new Troll();
aTroll.Walk();
}
}
And you can see how this starts to get messy. You could use an interface here so that your front end would be written once and (here's the important bit) tested, and you can then plug in further back end items as required:
interface ICreature
{
void Walk(int distance)
}
public class Troll : ICreature
public class Orc : ICreature
//etc
Front end is then:
void SpawnCreature(creatureType)
{
ICreature creature;
switch(creatureType)
{
case Orc:
creature = new Orc();
case Troll:
creature = new Troll();
}
creature.Walk();
}
The front end now only cares about the interface ICreature - it's not bothered about the internal implementation of a troll or an orc, but only on the fact that they implement ICreature.
An important point to note when looking at this from this point of view is that you could also easily have used an abstract creature class, and from this perspective, this has the same effect.
And you could extract the creation out to a factory:
public class CreatureFactory {
public ICreature GetCreature(creatureType)
{
ICreature creature;
switch(creatureType)
{
case Orc:
creature = new Orc();
case Troll:
creature = new Troll();
}
return creature;
}
}
And our front end would then become:
CreatureFactory _factory;
void SpawnCreature(creatureType)
{
ICreature creature = _factory.GetCreature(creatureType);
creature.Walk();
}
The front end now does not even have to have a reference to the library where Troll and Orc are implemented (providing the factory is in a separate library) - it need know nothing about them whatsoever.
B: Say you have functionality that only some creatures will have in your otherwise homogenous data structure, e.g.
interface ICanTurnToStone
{
void TurnToStone();
}
public class Troll: ICreature, ICanTurnToStone
Front end could then be:
void SpawnCreatureInSunlight(creatureType)
{
ICreature creature;
switch(creatureType)
{
case Orc:
creature = new Orc();
case Troll:
creature = new Troll();
}
creature.Walk();
if (creature is ICanTurnToStone)
{
(ICanTurnToStone)creature.TurnToStone();
}
}
C: Usage for dependency injection
Most dependency injection frameworks are easier to work with when there is a very loose coupling between the front end code and the back end implementation. If we take our factory example above and have our factory implement an interface:
public interface ICreatureFactory {
ICreature GetCreature(string creatureType);
}
Our front end could then have this injected (e.g an MVC API controller) through the constructor (typically):
public class CreatureController : Controller {
private readonly ICreatureFactory _factory;
public CreatureController(ICreatureFactory factory) {
_factory = factory;
}
public HttpResponseMessage TurnToStone(string creatureType) {
ICreature creature = _factory.GetCreature(creatureType);
creature.TurnToStone();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
With our DI framework (e.g. Ninject or Autofac), we can set them up so that at runtime a instance of CreatureFactory will be created whenever an ICreatureFactory is needed in an constructor - this makes our code nice and simple.
It also means that when we write a unit test for our controller, we can provide a mocked ICreatureFactory (e.g. if the concrete implementation required DB access, we don't want our unit tests dependent on that) and easily test the code in our controller.
D: There are other uses e.g. you have two projects A and B that for 'legacy' reasons are not well structured, and A has a reference to B.
You then find functionality in B that needs to call a method already in A. You can't do it using concrete implementations as you get a circular reference.
You can have an interface declared in B that the class in A then implements. Your method in B can be passed an instance of a class that implements the interface with no problem, even though the concrete object is of a type in A.
SortedList
Though it took a while, Java 8 does have a sorted List
.
http://docs.oracle.com/javase/8/javafx/api/javafx/collections/transformation/SortedList.html
As you can see in the javadocs, it is part of the JavaFX collections, intended to provide a sorted view on an ObservableList.
Update: Note that with Java 11, the JavaFX toolkit has moved outside the JDK and is now a separate library. JavaFX 11 is available as a downloadable SDK or from MavenCentral. See https://openjfx.io
Notice that in most suggestions the initial random value that you have got from rand() function, which is typically from 0 to RAND_MAX, is simply wasted. You are creating only one random number out of it, while there is a sound procedure that can give you more.
Assume that you want [min,max] region of integer random numbers. We start from [0, max-min]
Take base b=max-min+1
Start from representing a number you got from rand() in base b.
That way you have got floor(log(b,RAND_MAX)) because each digit in base b, except possibly the last one, represents a random number in the range [0, max-min].
Of course the final shift to [min,max] is simple for each random number r+min.
int n = NUM_DIGIT-1;
while(n >= 0)
{
r[n] = res % b;
res -= r[n];
res /= b;
n--;
}
If NUM_DIGIT is the number of digit in base b that you can extract and that is
NUM_DIGIT = floor(log(b,RAND_MAX))
then the above is as a simple implementation of extracting NUM_DIGIT random numbers from 0 to b-1 out of one RAND_MAX random number providing b < RAND_MAX.
I was recently looking for a nice solution to this without adding React-Bootstrap to my project (as Bootstrap 4 is about to be released).
This is my solution: https://jsfiddle.net/16j1se1q/1/
let Modal = React.createClass({
componentDidMount(){
$(this.getDOMNode()).modal('show');
$(this.getDOMNode()).on('hidden.bs.modal', this.props.handleHideModal);
},
render(){
return (
<div className="modal fade">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 className="modal-title">Modal title</h4>
</div>
<div className="modal-body">
<p>One fine body…</p>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" className="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
)
},
propTypes:{
handleHideModal: React.PropTypes.func.isRequired
}
});
let App = React.createClass({
getInitialState(){
return {view: {showModal: false}}
},
handleHideModal(){
this.setState({view: {showModal: false}})
},
handleShowModal(){
this.setState({view: {showModal: true}})
},
render(){
return(
<div className="row">
<button className="btn btn-default btn-block" onClick={this.handleShowModal}>Open Modal</button>
{this.state.view.showModal ? <Modal handleHideModal={this.handleHideModal}/> : null}
</div>
);
}
});
React.render(
<App />,
document.getElementById('container')
);
The main idea is to only render the Modal component into the React DOM when it is to be shown (in the App components render function). I keep some 'view' state that indicates whether the Modal is currently shown or not.
The 'componentDidMount' and 'componentWillUnmount' callbacks either hide or show the modal (once it is rendered into the React DOM) via Bootstrap javascript functions.
I think this solution nicely follows the React ethos but suggestions are welcome!
HTML:
<input type="checkbox" id="attraction" checked="checked" onchange="updateMap()">poi.attraction</input>
JavaScript:
function updateMap() {
map.setOptions({'styles': getStyles() });
}
function getStyles() {
var styles = [];
for (var i=0; i < types.length; i++) {
var style = {};
var type = types[i];
var enabled = document.getElementById(type).checked;
style['featureType'] = 'poi.' + type;
style['elementType'] = 'labels';
style['stylers'] = [{'visibility' : (enabled ? 'on' : 'off') }];
styles.push(style);
}
return styles;
}
You just need to make the siprimo and volteado methods static.
private static bool siprimo(long a)
and
private static long volteado(long a)
You can label each line separately, in your case:
\begin{align}
\lambda_i + \mu_i = 0 \label{eq:1}\\
\mu_i \xi_i = 0 \label{eq:2}\\
\lambda_i [y_i( w^T x_i + b) - 1 + \xi_i] = 0 \label{eq:3}
\end{align}
Note that this only works for AMS environments that are designed for multiple equations (as opposed to multiline single equations).
You can use parameters like that
<jsp:include page='about.jsp'>
<jsp:param name="articleId" value=""/>
</jsp:include>
and
in about.jsp you can take the paramter
<%String leftAds = request.getParameter("articleId");%>
Step1: copy all the rpm pkg in given locations
Step2: if createrepo is not already installed, as it will not be by default, install it.
[root@pavangildamysql1 8.0.11_rhel7]# yum install createrepo
Step3: create repository metedata and give below permission
[root@pavangildamysql1 8.0.11_rhel7]# chown -R root.root /scratch/PVN/8.0.11_rhel7
[root@pavangildamysql1 8.0.11_rhel7]# createrepo /scratch/PVN/8.0.11_rhel7
Spawning worker 0 with 3 pkgs
Spawning worker 1 with 3 pkgs
Spawning worker 2 with 3 pkgs
Spawning worker 3 with 2 pkgs
Workers Finished
Saving Primary metadata
Saving file lists metadata
Saving other metadata
Generating sqlite DBs
Sqlite DBs complete
[root@pavangildamysql1 8.0.11_rhel7]# chmod -R o-w+r /scratch/PVN/8.0.11_rhel7
Step4: Create repository file with following contents at /etc/yum.repos.d/mysql.repo
[local]
name=My Awesome Repo
baseurl=file:///scratch/PVN/8.0.11_rhel7
enabled=1
gpgcheck=0
Step5 Run this command to install
[root@pavangildamysql1 local]# yum --nogpgcheck localinstall mysql-commercial-server-8.0.11-1.1.el7.x86_64.rpm
After you determine that a number is composite (not prime), your work is done. You can exit the loop with break
.
while num > a :
if num%a==0 & a!=num:
print('not prime')
break # not going to update a, going to quit instead
else:
print('prime')
a=(num)+1
Also, you might try and become more familiar with some constructs in Python. Your loop can be shortened to a one-liner that still reads well in my opinion.
any(num % a == 0 for a in range(2, num))
This is documented in section 3.9.3 of the Spring 3.0 manual:
For a fallback match, the bean name is considered a default qualifier value.
In other words, the default behaviour is as though you'd added @Qualifier("country")
to the setter method.
Pooja Mane's answer worked for me, but I had to put the client_max_body_size variable inside of http section.
AFAIK, there is nothing built in for searching all columns. You can use Find
only against the primary key. Select
needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.
You can use the fingerprintJS2 library, it helps a lot with calculating a browser fingerprint.
By the way, on Panopticlick you can see how unique this usually is.
Howard's answer is concise and elegant, but it's also O(n^2) in the worst case. For large lists with large numbers of grouping key values, you'll want to sort the list first and then use itertools.groupby
:
>>> from itertools import groupby
>>> from operator import itemgetter
>>> seq = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
>>> seq.sort(key = itemgetter(1))
>>> groups = groupby(seq, itemgetter(1))
>>> [[item[0] for item in data] for (key, data) in groups]
[['A', 'C'], ['B'], ['D', 'E']]
Edit:
I changed this after seeing eyequem's answer: itemgetter(1)
is nicer than lambda x: x[1]
.
Though this is an old question, I've been looking for this. Here's my compilation of some solutions answered here and some other ideas found elsewhere to get a one-size-fits-all solution.
CODE :
// Post to browser console
function console($data, $is_error = false, $file = false, $ln = false) {
if(!function_exists('console_wer')) {
function console_wer($data, $is_error = false, $bctr, $file, $ln) {
echo '<div display="none">'.'<script type="text/javascript">'.(($is_error!==false) ? 'if(typeof phperr_to_cns === \'undefined\') { var phperr_to_cns = 1; document.addEventListener("DOMContentLoaded", function() { setTimeout(function(){ alert("Alert. see console."); }, 4000); }); }' : '').' console.group("PHP '.(($is_error) ? 'error' : 'log').' from "+window.atob("'.base64_encode((($file===false) ? $bctr['file'] : $file)).'")'.((($ln!==false && $file!==false) || $bctr!==false) ? '+" on line '.(($ln===false) ? $bctr['line'] : $ln).' :"' : '+" :"').'); console.'.(($is_error) ? 'error' : 'log').'('.((is_array($data)) ? 'JSON.parse(window.atob("'.base64_encode(json_encode($data)).'"))' : '"'.$data.'"').'); console.groupEnd();</script></div>'; return true;
}
}
return @console_wer($data, $is_error, (($file===false && $ln===false) ? array_shift(debug_backtrace()) : false), $file, $ln);
}
//PHP Exceptions handler
function exceptions_to_console($svr, $str, $file, $ln) {
if(!function_exists('severity_tag')) {
function severity_tag($svr) {
$names = [];
$consts = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true));
foreach ($consts as $code => $name) {
if ($svr & $code) $names []= $name;
}
return join(' | ', $names);
}
}
if (error_reporting() == 0) {
return false;
}
if(error_reporting() & $svr) {
console(severity_tag($svr).' : '.$str, true, $file, $ln);
}
}
// Divert php error traffic
error_reporting(E_ALL);
ini_set("display_errors", "1");
set_error_handler('exceptions_to_console');
TESTS & USAGE :
Usage is simple. Include first function for posting to console manually. Use second function for diverting php exception handling. Following test should give an idea.
// Test 1 - Auto - Handle php error and report error with severity info
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (Exception $e) {
echo "jsdlkjflsjfkjl";
}
// Test 2 - Manual - Without explicitly providing file name and line no.
console(array(1 => "Hi", array("hellow")), false);
// Test 3 - Manual - Explicitly providing file name and line no.
console(array(1 => "Error", array($some_result)), true, 'my file', 2);
// Test 4 - Manual - Explicitly providing file name only.
console(array(1 => "Error", array($some_result)), true, 'my file');
EXPLANATION :
The function console($data, $is_error, $file, $fn)
takes string or array as first argument and posts it on console using js inserts.
Second argument is a flag to differentiate normal logs against errors. For errors, we're adding event listeners to inform us through alerts if any errors were thrown, also highlighting in console. This flag is defaulted to false.
Third and fourth arguments are explicit declarations of file and line numbers, which is optional. If absent, they're defaulted to using the predefined php function debug_backtrace()
to fetch them for us.
Next function exceptions_to_console($svr, $str, $file, $ln)
has four arguments in the order called by php default exception handler. Here, the first argument is severity, which we further crosscheck with predefined constants using function severity_tag($code)
to provide more info on error.
NOTICE :
Above code uses JS functions and methods that are not available in older browsers. For compatibility with older versions, it needs replacements.
Above code is for testing environments, where you alone have access to the site. Do not use this in live (production) websites.
SUGGESTIONS :
First function console()
threw some notices, so I've wrapped them within another function and called it using error control operator '@'. This can be avoided if you didn't mind the notices.
Last but not least, alerts popping up can be annoying while coding. For this I'm using this beep (found in solution : https://stackoverflow.com/a/23395136/6060602) instead of popup alerts. It's pretty cool and possibilities are endless, you can play your favorite tunes and make coding less stressful.
Thought i'd add my solution that i've been using.
If you're using the System.Web.Script.Serialization.JavaScriptSerializer()
then the time returned isn't going to be specific to your timezone. To fix this you'll also want to use dte.getTimezoneOffset()
to get it back to your correct time.
String.prototype.toDateFromAspNet = function() {
var dte = eval("new " + this.replace(/\//g, '') + ";");
dte.setMinutes(dte.getMinutes() - dte.getTimezoneOffset());
return dte;
}
now you'll just call
"/Date(1245398693390)/".toDateFromAspNet();
Fri Jun 19 2009 00:04:53 GMT-0400 (Eastern Daylight Time) {}
Just add this after jQuery loads and before your code.
$(window).ajaxComplete(function () {console.log('Ajax Complete'); });
$(window).ajaxError(function (data, textStatus, jqXHR) {console.log('Ajax Error');
console.log('data: ' + data);
console.log('textStatus: ' + textStatus);
console.log('jqXHR: ' + jqXHR); });
$(window).ajaxSend(function () {console.log('Ajax Send'); });
$(window).ajaxStart(function () {console.log('Ajax Start'); });
$(window).ajaxStop(function () {console.log('Ajax Stop'); });
$(window).ajaxSuccess(function () {console.log('Ajax Success'); });
Solution:
ul {
font-size: 0;
}
ul li {
font-size: 14px;
display: inline-block;
}
You must set parent font size to 0
Maybe one of the easiest solutions would be to use the x
descriptor of the srcset
attribute as such:
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />
<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />
<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
Currently supported by all browsers except IE. (caniuse)
Enumerate basically gives you an index to work with in the for loop. So:
for i,a in enumerate([4, 5, 6, 7]):
print i, ": ", a
Would print:
0: 4
1: 5
2: 6
3: 7
With Intellij Toggle Skip Test Mode can be used from Maven Projects tab:
For Windows 10
Look for the jupyter_notebook_config.py in C:\Users\your_user_name\.jupyter or look it up with cortana.
If you don't have it, then go to the cmd line and type:
jupyter notebook --generate-config
Open the jupyter_notebook_config.py and do a ctrl-f
search for:
c.NotebookApp.notebook_dir
Uncomment it by removing the #.
Change it to:
c.NotebookApp.notebook_dir = 'C:/your/new/path'
Note: You can put a u
in front of the first '
, change \\\\
to /
, or change the '
to "
. I don't think it matters.
Go to your Jupyter Notebook link and right click it. Select properties. Go to the Shortcut menu and click Target. Look for %USERPROFILE%. Delete it. Save. Restart Jupyter.
My solution to not having sessionStorage transferable over tabs was to create a localProfile and bang off this variable. If this variable is set but my sessionStorage variables arent go ahead and reinitialize them. When user logs out window closes destroy this localStorage variable
Just use CSS transitions:
$(element).css( { transition: "transform 0.5s",
transform: "rotate(" + amount + "deg)" } );
setTimeout( function() { $(element).css( { transition: "none" } ) }, 500 );
As example I set the duration of the animation to 0.5 seconds.
Note the setTimeout
to remove the transition
css property after the animation is over (500 ms)
For readability I omitted vendor prefixes.
This solution requires browser's transition support off course.
Use this code to generate horizontal scrolling blocks contents. I got this from here http://www.htmlexplorer.com/2014/02/horizontal-scrolling-webpage-content.html
<html>
<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<head>
<style type="text/css">
#outer_wrapper {
overflow: scroll;
width:100%;
}
#outer_wrapper #inner_wrapper {
width:6000px; /* If you have more elements, increase the width accordingly */
}
#outer_wrapper #inner_wrapper div.box { /* Define the properties of inner block */
width: 250px;
height:300px;
float: left;
margin: 0 4px 0 0;
border:1px grey solid;
}
</style>
</head>
<body>
<div id="outer_wrapper">
<div id="inner_wrapper">
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<!-- more boxes here -->
</div>
</div>
</body>
</html>
There are a couple of methods for full mysql FULL [OUTER] JOIN.
UNION a left join and right join. UNION will remove duplicates by performing an ORDER BY operation. So depending on your data, it may not be performant.
SELECT * FROM A
LEFT JOIN B ON A.key = B.key
UNION
SELECT * FROM A
RIGHT JOIN B ON A.key = B.key
UNION ALL a left join and right EXCLUDING join (that's the lower right figure in the diagram). UNION ALL will not remove duplicates. Sometimes this might be the behaviour that you want. You also want to use RIGHT EXCLUDING to avoid duplicating common records from selection A and selection B - i.e Left join has already included common records from selection B, lets not repeat that again with the right join.
SELECT * FROM A
LEFT JOIN B ON A.key = B.key
UNION ALL
SELECT * FROM A
RIGHT JOIN B ON A.key = B.key
WHERE A.key IS NULL
This is the simplest way to remove all the packages. From an admin prompt:
wmic product where "name like 'microsoft visual%'" call uninstall /nointeractive
Repeat for SQL etc by replacing visual%
in above command with sql
.
Thankfully, it's not possible to change the duration of the vibration. The only way to trigger the vibration is to play the kSystemSoundID_Vibrate
as you have. If you really want to though, what you can do is to repeat the vibration indefinitely, resulting in a pulsing vibration effect instead of a long continuous one. To do this, you need to register a callback function that will get called when the vibration sound that you play is complete:
AudioServicesAddSystemSoundCompletion (
kSystemSoundID_Vibrate,
NULL,
NULL,
MyAudioServicesSystemSoundCompletionProc,
NULL
);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Then you define your callback function to replay the vibrate sound again:
#pragma mark AudioService callback function prototypes
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
);
#pragma mark AudioService callback function implementation
// Callback that gets called after we finish buzzing, so we
// can buzz a second time.
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
) {
if (iShouldKeepBuzzing) { // Your logic here...
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
} else {
//Unregister, so we don't get called again...
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
}
I add a picture, show config
difference between mirror and bare.
The left is bare, right is mirror. You can be clear, mirror's config file have fetch
key, which means you can update it,by git remote update
or git fetch --all
If you won't go with regex:
"ABCDEFGHIJKLMNOP".toLowerCase().contains("gHi".toLowerCase())
You're almost here, you're just missing a few things:
PUT /test
{
"mappings": {
"type_name": { <--- add the type name
"properties": { <--- enclose all field definitions in "properties"
"field1": {
"type": "integer"
},
"field2": {
"type": "integer"
},
"field3": {
"type": "string",
"index": "not_analyzed"
},
"field4,": {
"type": "string",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
}
},
"settings": {
...
}
}
UPDATE
If your index already exists, you can also modify your mappings like this:
PUT test/_mapping/type_name
{
"properties": { <--- enclose all field definitions in "properties"
"field1": {
"type": "integer"
},
"field2": {
"type": "integer"
},
"field3": {
"type": "string",
"index": "not_analyzed"
},
"field4,": {
"type": "string",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
}
UPDATE:
As of ES 7, mapping types have been removed. You can read more details here
Honestly you can take a look at this class that I built which does basic file operations. The write method overwrites and append keeps old data.
class IO:
def read(self, filename):
toRead = open(filename, "rb")
out = toRead.read()
toRead.close()
return out
def write(self, filename, data):
toWrite = open(filename, "wb")
out = toWrite.write(data)
toWrite.close()
def append(self, filename, data):
append = self.read(filename)
self.write(filename, append+data)
You aren't building your formula right.
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = "=SUM(H5:H" & var1a & ")"
This does the same as the following lines do:
Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"
which is what you are trying to do.
Also, you want to have the =
at the beginning of the formala.
Now I've found the problem.
Removing the obj_exception_throw
from my breakpoints solved this. Now it's caught by the @try
block and also, NSSetUncaughtExceptionHandler
will handle this if a @try
block is missing.
You can use the following code for changing the String value into the time equivalent:
String str = "08:03:10 pm";
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = (Date)formatter.parse(str);
Hope this helps you.
Try this code.
<input type="button" value="Open Window"
onclick="window.open('http://www.google.com')">
There's no hard and fast rule. The documentation for a class should indicate whether subclasses should call the superclass method. Sometimes you want to completely replace superclass behaviour, and at other times augment it - i.e. call your own code before and/or after a superclass call.
Update: The same basic logic applies to any method call. Constructors sometimes need special consideration (as they often set up state which determines behaviour) and destructors because they parallel constructors (e.g. in the allocation of resources, e.g. database connections). But the same might apply, say, to the render()
method of a widget.
Further update: What's the OPP? Do you mean OOP? No - a subclass often needs to know something about the design of the superclass. Not the internal implementation details - but the basic contract that the superclass has with its clients (using classes). This does not violate OOP principles in any way. That's why protected
is a valid concept in OOP in general (though not, of course, in Python).
This is not possible. Linux permissions and windows permissions do not translate. They are machine specific. It would be a security hole to allow permissions to be set on files before they even arrive on the target system.
Simply use the jQuery Trigger event
like so:
$('form').trigger("reset");
This will reset checkboxes, radiobuttons, textboxes, etc... Essentially it turns your form to it's default state. Simply put the #ID, Class, element
inside the jQuery
selector.
Try this:
<iframe name="iframe1" src="target.html"></iframe>
<a href="link.html" target="iframe1">link</a>
The "target" attribute should open in the iframe.
I'd love to post this as a comment to Tendayi Mawushe's answer, but I'm afraid there is not enough space ;)
This is the relevant part from the Apache Commons UrlValidator source:
/**
* This expression derived/taken from the BNF for URI (RFC2396).
*/
private static final String URL_PATTERN =
"/^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/";
// 12 3 4 5 6 7 8 9
/**
* Schema/Protocol (ie. http:, ftp:, file:, etc).
*/
private static final int PARSE_URL_SCHEME = 2;
/**
* Includes hostname/ip and port number.
*/
private static final int PARSE_URL_AUTHORITY = 4;
private static final int PARSE_URL_PATH = 5;
private static final int PARSE_URL_QUERY = 7;
private static final int PARSE_URL_FRAGMENT = 9;
You can easily build your own validator from there.
For me, running the ad-hoc network on Windows 8.1, it was two things:
Any IP will allow you to connect, but if you want internet access the static IP should match the subnet from the shared internet connection.
I'm not sure why I couldn't get a longer password to work, but it's worth a try. Maybe a more knowledgeable person could fill us in.
Table variables are just like int or varchar variables.
You don't need to drop them. They have the same scope rules as int or varchar variables
The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.
You should be able to accomplish this by adding a refspec for tags to your local config. Concretely:
[remote "upstream"]
url = <redacted>
fetch = +refs/heads/*:refs/remotes/upstream/*
fetch = +refs/tags/*:refs/tags/*
Only thing that worked is
android:lineSpacingExtra="-8dp"
A small addition to the excellent answers given: If you're running with a non-ajax backup solution for users without javascript, you will have to get those server-side headers correct anyway. This is not impossible, although I understand those that give it up ;)
I'm sure there's another question on SO that will give you the full set of headers that are appropriate. I am not entirely conviced miceus reply covers all the bases 100%.
If you are using PL/SQL you can also use DBMS_ASSERT
it can sanitize your input so you can use it without worrying about SQL injections.
see this answer for instance: https://stackoverflow.com/a/21406499/1726419
This is in answer to your question...
I'd also like to know how to make it open up in Sublime Text 2 instead
For Windows:
git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"
Check that the path for sublime_text.exe
is correct and adjust if needed.
For Mac/Linux:
git config --global core.editor "subl -n -w"
If you get an error message such as:
error: There was a problem with the editor 'subl -n -w'.
Create the alias for subl
sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
Again check that the path matches for your machine.
For Sublime Text simply save cmd S
and close the window cmd W
to return to git.
Use sp_rename
EXEC sp_RENAME 'TableName.OldColumnName' , 'NewColumnName', 'COLUMN'
See: SQL SERVER – How to Rename a Column Name or Table Name
Documentation: sp_rename (Transact-SQL)
For your case it would be:
EXEC sp_RENAME 'table_name.old_name', 'new_name', 'COLUMN'
Remember to use single quotes to enclose your values.
const mapObject = (obj = {}, mapper) =>
Object.entries(obj).reduce(
(acc, [key, val]) => ({ ...acc, [key]: mapper(val) }),
{},
);
I would state it with the following analogy:
+-----------------------------+-------+-----------+
| Domain | Meta | Concrete |
+-----------------------------+-------+-----------+
| Docker | Image | Container |
| Object oriented programming | Class | Object |
+-----------------------------+-------+-----------+
Following is simple method to generate specific length verification code. Length can be specified, by default, it generates 4 digit code.
function get_sms_token($length = 4) {
return rand(
((int) str_pad(1, $length, 0, STR_PAD_RIGHT)),
((int) str_pad(9, $length, 9, STR_PAD_RIGHT))
);
}
echo get_sms_token(6);
You can use PhoneNumberUtils
if your phone format is one of the described formats. If none of the utility function match your needs, use regular experssions.