This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
Powershell version of command for git repo name:
(git config --get remote.origin.url) -replace '.*/' -replace '.git'
The correct answer will be to add
android:backgroundTint="#ff00ff"
to the tool bar
with
android:background="@android:color/white"
If you use other color then white for the background it will remove the shadow. Nice one Google!
I need to do this frequently, so I use this:
var loadJS = function(url, implementationCode, location){
//url is URL of external file, implementationCode is the code
//to be called from the file, location is the location to
//insert the <script> element
var scriptTag = document.createElement('script');
scriptTag.src = url;
scriptTag.onload = implementationCode;
scriptTag.onreadystatechange = implementationCode;
location.appendChild(scriptTag);
};
var yourCodeToBeCalled = function(){
//your code goes here
}
loadJS('yourcode.js', yourCodeToBeCalled, document.body);
For more information, see this site How do I include a JavaScript file in another JavaScript file?, which is the source of my function idea.
I tried this on the command line using
D:\>xcopy myfile.dat xcopytest\test\
and the target directory was properly created.
If not you can create the target dir using the mkdir
command with cmd
's command extensions enabled like
cmd /x /c mkdir "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\"
('/x' enables command extensions in case they're not enabled by default on your system, I'm not that familiar with cmd
)
use
cmd /?
mkdir /?
xcopy /?
for further information :)
The Android Studio website has recently (I think) provided some advice what kind of messages to expect from different log levels that may be useful along with Kurtis' answer:
The problem is twofold:
.
in the routeBy default, IIS treats all URI's with a dot in them as static resource, tries to return it and skip further processing (by Web API) altogether. This is configured in your Web.config in the section system.webServer.handlers
: the default handler handles path="*."
. You won't find much documentation regarding the strange syntax in this path
attribute (regex would have made more sense), but what this apparently means is "anything that doesn't contain a dot" (and any character from point 2 below). Hence the 'Extensionless' in the name ExtensionlessUrlHandler-Integrated-4.0
.
Multiple solutions are possible, in my opinion in the order of 'correctness':
path="*."
attribute to path="*"
. It will then catch everything. Note that from then on, your web api will no longer interpret incoming calls with dots as static resources! If you are hosting static resources on your web api, this is therefor not advised!<system.webserver>
: <modules runAllManagedModulesForAllRequests="true">
:
in the routeAfter you've changed the above, by default, you'd get the following error:
A potentially dangerous Request.Path value was detected from the client (:).
You can change the predefined disallowed/invalid characters in your Web.config. Under <system.web>
, add the following: <httpRuntime requestPathInvalidCharacters="<,>,%,&,*,\,?" />
. I've removed the :
from the standard list of invalid characters.
Although not an answer to your question, a safer and easier solution would be to change the request so that all this is not required. This can be done in two ways:
?date=2012-12-31T22:00:00.000Z
..000
from every request. You'd still need to allow :
's (cfr point 2).Shawn Wildermuth has a nice guide here: https://wildermuth.com/2017/11/19/ASP-NET-Core-2-0-and-the-End-of-Bower
The article links to the gulpfile on GitHub where he's implemented the strategy in the article. You could just copy and paste most of the gulpfile contents into yours, but be sure to add the appropriate packages in package.json under devDependencies: gulp gulp-uglify gulp-concat rimraf merge-stream
-num will equal to num for Integer.MIN_VALUE as
Integer.MIN_VALUE = Integer.MIN_VALUE * -1
I finally solved this problem. I used Samsung Galaxy S with Froyo. The "port" below is the same port what you use for the emulator (10.0.2.2:port). What I did:
http://192.168.x.x:port/test.php
It should now work.
I added to the migration itself
Schema::defaultStringLength(191);
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
yes, I know I need to consider it on every migration but I would rather that than have it tucked away in some completely unrelated service provider
Try this:
declare @csv varchar(100) ='aaa,bb,csda,daass';
set @csv = @csv+',';
with cte as
(
select SUBSTRING(@csv,1,charindex(',',@csv,1)-1) as val, SUBSTRING(@csv,charindex(',',@csv,1)+1,len(@csv)) as rem
UNION ALL
select SUBSTRING(a.rem,1,charindex(',',a.rem,1)-1)as val, SUBSTRING(a.rem,charindex(',',a.rem,1)+1,len(A.rem))
from cte a where LEN(a.rem)>=1
) select val from cte
string tail = test.Substring(test.LastIndexOf('-') + 1);
Open Network and Sharing Center and go to the Change adapter settings in the sidebar.
Right-click on the host-only adapter in the list of adapters and then Configure button -> Driver tab -> Update driver button.
Select Browse my computer ... and in the next dialog select Let me pick .... You should see the list with just host-only driver in it.
Select it and click next. After the driver is updated, please try using host-only network in a VM again.
I had done all the above solutions but it did not work.
My default page wasn't an aspx page, it was an html page.
This article solved the problem. https://weblog.west-wind.com/posts/2013/aug/15/iis-default-documents-vs-aspnet-mvc-routes
Basically, in my \App_Start\RouteConfig.cs file, I had to add a line:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute(""); // This was the line I had to add here!
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Hope this helps someone, it took me a goodly while to find the answer.
Should work in all cases:
SELECT regexp_replace(0.1234, '^(-?)([.,])', '\10\2') FROM dual
max(files, key = os.path.getctime)
is quite incomplete code. What is files
? It probably is a list of file names, coming out of os.listdir()
.
But this list lists only the filename parts (a. k. a. "basenames"), because their path is common. In order to use it correctly, you have to combine it with the path leading to it (and used to obtain it).
Such as (untested):
def newest(path):
files = os.listdir(path)
paths = [os.path.join(path, basename) for basename in files]
return max(paths, key=os.path.getctime)
For Atlassian Connect Apps, use
AP.navigator.reload();
See details here
This answer didn't work for me, I needed to run html decode on the string also. See
iconv('UTF-8', 'windows-1252', html_entity_decode($str));
Props go to emfi from html_entity_decode in FPDF(using tFPDF extention)
Try the following:
JS file
this.options = {
languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);
HTML file
<div class="form-group col-sm-6">
<label>Preferred language</label>
<select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
</select>
</div>
The error is from this:
def playSound(myList):
for i in range(myList): # <= myList is a list, not an integer
You cannot pass a list to range
which expects an integer. Most likely, you meant to do:
def playSound(myList):
for list_item in myList:
OR
def playSound(myList):
for i in range(len(myList)):
OR
def playSound(myList):
for i, list_item in enumerate(myList):
Download and install SAP Crystal Reports Runtime engine for .net (32 bit or 64 bit) depending on your os version. Should work there after
This works great if a straight copy is in order. If the situation calls for creating new objects from templates, I usually wrap the template div in a hidden storage div and use jquery's html() in conjunction with clone() applying the following technique:
<style>
#element-storage {
display: none;
top: 0;
right: 0;
position: fixed;
width: 0;
height: 0;
}
</style>
<script>
$("#new-div").append($("#template").clone().html(function(index, oldHTML){
// .. code to modify template, e.g. below:
var newHTML = "";
newHTML = oldHTML.replace("[firstname]", "Tom");
newHTML = newHTML.replace("[lastname]", "Smith");
// newHTML = newHTML.replace(/[Example Replace String]/g, "Replacement"); // regex for global replace
return newHTML;
}));
</script>
<div id="element-storage">
<div id="template">
<p>Hello [firstname] [lastname]</p>
</div>
</div>
<div id="new-div">
</div>
The correct answer is, that, because the '%'
-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName
(be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'
or, in your example:
DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'
Since I need the ImageView to add an icon just for aesthetics I've added tools:ignore="ContentDescription"
within each ImageView I had in my xml file.
I'm no longer getting any error messages
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Based on the previous reply, mainly @fcalderan, this marquee scrolls when hovered, with the advantage that the animation scrolls completely even if the text is shorter than the space within it scrolls, also any text length takes the same amount of time (this may be a pros or a cons) when not hovered the text return in the initial position.
No hardcoded value other than the scroll time, best suited for small scroll spaces
.marquee {_x000D_
width: 100%;_x000D_
margin: 0 auto;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
box-sizing: border-box;_x000D_
display: inline-flex; _x000D_
}_x000D_
_x000D_
.marquee span {_x000D_
display: flex; _x000D_
flex-basis: 100%;_x000D_
animation: marquee-reset;_x000D_
animation-play-state: paused; _x000D_
}_x000D_
_x000D_
.marquee:hover> span {_x000D_
animation: marquee 2s linear infinite;_x000D_
animation-play-state: running;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
0% {_x000D_
transform: translate(0%, 0);_x000D_
} _x000D_
50% {_x000D_
transform: translate(-100%, 0);_x000D_
}_x000D_
50.001% {_x000D_
transform: translate(100%, 0);_x000D_
}_x000D_
100% {_x000D_
transform: translate(0%, 0);_x000D_
}_x000D_
}_x000D_
@keyframes marquee-reset {_x000D_
0% {_x000D_
transform: translate(0%, 0);_x000D_
} _x000D_
}
_x000D_
<span class="marquee">_x000D_
<span>This is the marquee text</span>_x000D_
</span>
_x000D_
int
(including Python2's long
) can be converted to bytes
using following function:
import codecs
def int2bytes(i):
hex_value = '{0:x}'.format(i)
# make length of hex_value a multiple of two
hex_value = '0' * (len(hex_value) % 2) + hex_value
return codecs.decode(hex_value, 'hex_codec')
The reverse conversion can be done by another one:
import codecs
import six # should be installed via 'pip install six'
long = six.integer_types[-1]
def bytes2int(b):
return long(codecs.encode(b, 'hex_codec'), 16)
Both functions work on both Python2 and Python3.
You can use obj.constructor.name to check the "class" of an object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Function_names_in_classes
For Example
var error = new Error("ValidationError");
console.log(error.constructor.name);
The above line will log "Error" which is the class name of the object. This could be used with any classes in javascript, if the class is not using a property that goes by the name "name"
If @papigee does solution doesn't work, maybe you don't have the permissions.
I tried @papigee solution but does't work without sudo.
I did :
sudo docker exec -it <container id or name> /bin/sh
The problem with iPhone camera is that the first models (of which there are tons in use) have a fixed-focus camera that cannot take picture in-focus for distances under 2ft. The images are blurry and distorted and if taken from greater distance there is not enough detail/information from the barcode.
A few companies have developed iPhone apps that can accomodate for that by using advanced de-blurring technologies. Those applications you can find on Apple app store: pic2shop, RedLaser and ShopSavvy. All of the companies have announced that they have also SDKs available - some for free or very preferential terms, check that one out.
The msi
file extension is mapped to msiexec (same way typing a .txt filename on a command prompt launches Notepad/default .txt
file handler to display the file).
Thus typing in a filename with an .msi extension really runs msiexec with the MSI file as argument and takes the default action, install. For that reason, uninstalling requires you to invoke msiexec with uninstall switch to unstall it.
I've built up on @user1032613's answer and on this answer and created a "on press enter click element with querystring" hook. enjoy!
const { useEffect } = require("react");
const useEnterKeyListener = ({ querySelectorToExecuteClick }) => {
useEffect(() => {
//https://stackoverflow.com/a/59147255/828184
const listener = (event) => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
handlePressEnter();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);
const handlePressEnter = () => {
//https://stackoverflow.com/a/54316368/828184
const mouseClickEvents = ["mousedown", "click", "mouseup"];
function simulateMouseClick(element) {
mouseClickEvents.forEach((mouseEventType) =>
element.dispatchEvent(
new MouseEvent(mouseEventType, {
view: window,
bubbles: true,
cancelable: true,
buttons: 1,
})
)
);
}
var element = document.querySelector(querySelectorToExecuteClick);
simulateMouseClick(element);
};
};
export default useEnterKeyListener;
This is how you use it:
useEnterKeyListener({
querySelectorToExecuteClick: "#submitButton",
});
https://codesandbox.io/s/useenterkeylistener-fxyvl?file=/src/App.js:399-407
You can merge objects through following my method
var obj1 = { food: 'pizza', car: 'ford' };_x000D_
var obj2 = { animal: 'dog' };_x000D_
_x000D_
var result = mergeObjects([obj1, obj2]);_x000D_
_x000D_
console.log(result);_x000D_
document.write("result: <pre>" + JSON.stringify(result, 0, 3) + "</pre>");_x000D_
_x000D_
function mergeObjects(objectArray) {_x000D_
if (objectArray.length) {_x000D_
var b = "", i = -1;_x000D_
while (objectArray[++i]) {_x000D_
var str = JSON.stringify(objectArray[i]);_x000D_
b += str.slice(1, str.length - 1);_x000D_
if (objectArray[i + 1]) b += ",";_x000D_
}_x000D_
return JSON.parse("{" + b + "}");_x000D_
}_x000D_
return {};_x000D_
}
_x000D_
Since Jackson v2.0, you can use @JsonFormat annotation directly on Object members;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z")
private Date date;
If you're still having issues with the simple approach, creating an empty bucket then Redirect all requests to another host name
under Static web hosting in properties via the console. Ensure that you have set 2 A records in route53, one for final-destination.com
and one for redirect-to.final-destination.com
. The settings for each of these will be identical, but the name will be different so it matches the names that you set for your buckets / URLs.
I came up with this while trying to figure out how to display currency ('$' to left, number to right) in table cells:
<div class="currency">20.34</div>
.currency {
text-align: right;
}
.currency:before {
content: "$";
float: left;
padding-right: 4px;
}
I am pretty sure this is a duplicate. Anyway, have a look at the following piece of code
x <- seq(5, 15, length=1000)
y <- dnorm(x, mean=10, sd=3)
plot(x, y, type="l", lwd=1)
I'm sure you can work the rest out yourself, for the title you might want to look for something called main=
and y-axis
labels are also up to you.
If you want to see more of the tails of the distribution, why don't you try playing with the seq(5, 15, )
section? Finally, if you want to know more about what dnorm
is doing I suggest you look here
You could try writing to stderr, rather than stdout.
fprintf(stderr, "Hello, please enter your age\n");
You should also have a look at this relevant thread.
If you have bigger version than v4.9 of Highcharts you can use visible: false
in the xAxis
and yAxis
settings.
Example:
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Highcharts axis visibility'
},
xAxis: {
visible: false
},
yAxis: {
title: {
text: 'Fruit'
},
visible: false
}
});
Put the following at the very top of your file:
import sys
if float(sys.version.split()[0][:3]) < 2.7:
print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
exit(1)
Then continue on with the normal Python code:
import ...
import ...
other code...
You can use the following script to add swap on Amazon Linux.
https://github.com/chetankapoor/swap
Download the script using wget:
wget https://raw.githubusercontent.com/chetankapoor/swap/master/swap.sh -O swap.sh
Then run the script with the following format:
sh swap.sh 2G
For a complete tutorial you can visit:
But I need the match result to be ... not in a match group...
For what you are trying to do, this should work. \K
resets the starting point of the match.
\bObject Name:\s+\K\S+
You can do the same for getting your Security ID
matches.
\bSecurity ID:\s+\K\S+
Just call fig.tight_layout()
as you normally would. (pyplot
is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)
There shouldn't be a difference between the QtAgg
backend and the default backend (or if there is, it's a bug).
E.g.
import matplotlib.pyplot as plt
#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#-- we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
fig.tight_layout()
plt.show()
When trying to make changes to a Pandas dataframe using a function, we use 'inplace=True' if we want to commit the changes to the dataframe. Therefore, the first line in the following code changes the name of the first column in 'df' to 'Grades'. We need to call the database if we want to see the resulting database.
df.rename(columns={0: 'Grades'}, inplace=True)
df
We use 'inplace=False' (this is also the default value) when we don't want to commit the changes but just print the resulting database. So, in effect a copy of the original database with the committed changes is printed without altering the original database.
Just to be more clear, the following codes do the same thing:
#Code 1
df.rename(columns={0: 'Grades'}, inplace=True)
#Code 2
df=df.rename(columns={0: 'Grades'}, inplace=False}
This could be because you are missing an import.
Example:
ERROR in src/app/products/product-list.component.ts:15:15 - error TS2304: Cannot find name 'IProduct'.
Make sure you are adding the import at the top of the file:
import { IProduct } from './product';
...
export class ProductListComponent {
pageTitle: string = 'product list!';
imageWidth: number = 50;
imageMargin: number = 2;
showImage: boolean = false;
listFilter: string = 'cart';
products: IProduct[] = ... //cannot find name error
I think this could help..
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
if([AFNetworkReachabilityManager sharedManager].isReachable)
{
NSLog(@"Network reachable");
}
else
{
NSLog(@"Network not reachable");
}
Samsung Galaxy Ace advertises 158 MB of internal storage in its specifications, but the core applications and services consume about 110 MB of that (I used the task manager on the device to inspect this). My app was 52 MB, because it had a lot of assets. Once I deleted some of those down to 45 MB, the app managed to install without a problem. The device was still alerting me that internal storage was almost full, and I should uninstall some apps, even though I only had one app installed.
After installing a release version of the .apk bundle and then uninstalling it, my device displays 99 MB of free space, so it might be debugging information cluttering up the device after all. See Louis Semprini's answer.
You can use:
a.delete(a[0])
a.delete_at 0
Both can work
echo $TESTSTRINGONE|awk '{print substr($0,0,5)}'
In the controller action append to the header the following lines
public ActionResult Create(string PositionID)
{
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
You're thinking about this the wrong way. You're thinking in logical steps each time cin
or getline
is used. Ex. First ask for a number, then ask for a name. That is the wrong way to think about cin
. So you run into a race condition because you assume the stream is clear each time you ask for a input.
If you write your program purely for input you'll find the problem:
void main(void)
{
double num;
string mystr;
cin >> num;
getline(cin, mystr);
cout << "num=" << num << ",mystr=\'" << mystr << "\'" << endl;
}
In the above, you are thinking, "first get a number." So you type in 123
press enter, and your output will be num=123,mystr=''
. Why is that? It's because in the stream you have 123\n
and the 123
is parsed into the num
variable while \n
is still in the stream. Reading the doc for getline
function by default it will look in the istream
until a \n
is encountered. In this example, since \n
is in the stream, it looks like it "skipped" it but it worked properly.
For the above to work, you'll have to enter 123Hello World
which will properly output num=123,mystr='Hello World'
. That, or you put a cin.ignore
between the cin
and getline
so that it'll break into logical steps that you expect.
This is why you need the ignore
command. Because you are thinking of it in logical steps rather than in a stream form so you run into a race condition.
Take another code example that is commonly found in schools:
void main(void)
{
int age;
string firstName;
string lastName;
cout << "First name: ";
cin >> firstName;
cout << "Last name: ";
cin >> lastName;
cout << "Age: ";
cin >> age;
cout << "Hello " << firstName << " " << lastName << "! You are " << age << " years old!" << endl;
}
The above seems to be in logical steps. First ask for first name, last name, then age. So if you did John
enter, then Doe
enter, then 19
enter, the application works each logic step. If you think of it in "streams" you can simply enter John Doe 19
on the "First name:" question and it would work as well and appear to skip the remaining questions. For the above to work in logical steps, you would need to ignore
the remaining stream for each logical break in questions.
Just remember to think of your program input as it is reading from a "stream" and not in logical steps. Each time you call cin
it is being read from a stream. This creates a rather buggy application if the user enters the wrong input. For example, if you entered a character where a cin >> double
is expected, the application will produce a seemingly bizarre output.
You could use a simple regular expression to assert that the id only contains allowed characters, like so:
if(id.match(/^[0-9a-zA-Z]{1,16}$/)){
//The id is fine
}
else{
//The id is illegal
}
My example allows only alphanumerical characters, and strings of length 1 to 16, you should change it to match the type of ids that you use.
By the way, at line 6, the value property is missing a pair of quotes, an easy mistake to make when you quote on two levels.
I can't see your actual data flow, depending on context this check may not at all be needed, or it may not be enough. In order to make a proper security review we would need more information.
In general, about built in escape or sanitize functions, don't trust them blindly. You need to know exactly what they do, and you need to establish that that is actually what you need. If it is not what you need, the code your own, most of the time a simple whitelisting regex like the one I gave you works just fine.
.NET Core will install and run on macOS - and just about any other desktop OS.
IDEs are available for the mac, including:
Mono is a good option that I've used in the past. But with Core 3.0 out now, I would go that route.
Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work
Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant
sFileIn = "z:\docs\FileName.csv"
sFileOut = "z:\docs\FileOut.csv"
Set fs = CreateObject("Scripting.FileSystemObject")
Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading
sTmp = tsIn.ReadAll
Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
aryFile = Split(sTmp, vbCrLf)
''Start at line 3 and end at last line -1
For i = 3 To UBound(aryFile) - 1
tsOut.WriteLine aryFile(i)
Next
tsOut.Close
DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub
Edit re various comments
It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.
About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003
Introduction to importing and exporting data -- Applies to: Microsoft Access 2010
Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.
I think you can use loc
if you need update two columns to same value:
df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
stream feat another_feat
a 1 some_value some_value
b 2 aaaa aaaa
c 2 aaaa aaaa
d 3 some_value some_value
If you need update separate, one option is use:
df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
stream feat another_feat
a 1 some_value some_value
b 2 10 some_value
c 2 10 some_value
d 3 some_value some_value
Another common option is use numpy.where
:
df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
stream feat another_feat
a 1 20 some_value
b 2 10 some_value
c 2 10 some_value
d 3 20 some_value
EDIT: If you need divide all columns without stream
where condition is True
, use:
print df1
stream feat another_feat
a 1 4 5
b 2 4 5
c 2 2 9
d 3 1 7
#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']
df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
stream feat another_feat
a 1 4.0 5.0
b 2 2.0 2.5
c 2 1.0 4.5
d 3 1.0 7.0
If working with multiple conditions is possible use multiple numpy.where
or numpy.select
:
df0 = pd.DataFrame({'Col':[5,0,-6]})
df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing',
np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))
df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
['Increasing', 'Decreasing'],
default='No Change')
print (df0)
Col New Col1 New Col2
0 5 Increasing Increasing
1 0 No Change No Change
2 -6 Decreasing Decreasing
Adding to this answer here. This one adds support for mouse events for testing on desktop:
<!--scripts-->
class SwipeEventDispatcher {
constructor(element, options = {}) {
this.evtMap = {
SWIPE_LEFT: [],
SWIPE_UP: [],
SWIPE_DOWN: [],
SWIPE_RIGHT: []
};
this.xDown = null;
this.yDown = null;
this.element = element;
this.isMouseDown = false;
this.listenForMouseEvents = true;
this.options = Object.assign({ triggerPercent: 0.3 }, options);
element.addEventListener('touchstart', evt => this.handleTouchStart(evt), false);
element.addEventListener('touchend', evt => this.handleTouchEnd(evt), false);
element.addEventListener('mousedown', evt => this.handleMouseDown(evt), false);
element.addEventListener('mouseup', evt => this.handleMouseUp(evt), false);
}
on(evt, cb) {
this.evtMap[evt].push(cb);
}
off(evt, lcb) {
this.evtMap[evt] = this.evtMap[evt].filter(cb => cb !== lcb);
}
trigger(evt, data) {
this.evtMap[evt].map(handler => handler(data));
}
handleTouchStart(evt) {
this.xDown = evt.touches[0].clientX;
this.yDown = evt.touches[0].clientY;
}
handleMouseDown(evt) {
if (this.listenForMouseEvents==false) return;
this.xDown = evt.clientX;
this.yDown = evt.clientY;
this.isMouseDown = true;
}
handleMouseUp(evt) {
if (this.isMouseDown == false) return;
const deltaX = evt.clientX - this.xDown;
const deltaY = evt.clientY - this.yDown;
const distMoved = Math.abs(Math.abs(deltaX) > Math.abs(deltaY) ? deltaX : deltaY);
const activePct = distMoved / this.element.offsetWidth;
if (activePct > this.options.triggerPercent) {
if (Math.abs(deltaX) > Math.abs(deltaY)) {
deltaX < 0 ? this.trigger('SWIPE_LEFT') : this.trigger('SWIPE_RIGHT');
} else {
deltaY > 0 ? this.trigger('SWIPE_UP') : this.trigger('SWIPE_DOWN');
}
}
}
handleTouchEnd(evt) {
const deltaX = evt.changedTouches[0].clientX - this.xDown;
const deltaY = evt.changedTouches[0].clientY - this.yDown;
const distMoved = Math.abs(Math.abs(deltaX) > Math.abs(deltaY) ? deltaX : deltaY);
const activePct = distMoved / this.element.offsetWidth;
if (activePct > this.options.triggerPercent) {
if (Math.abs(deltaX) > Math.abs(deltaY)) {
deltaX < 0 ? this.trigger('SWIPE_LEFT') : this.trigger('SWIPE_RIGHT');
} else {
deltaY > 0 ? this.trigger('SWIPE_UP') : this.trigger('SWIPE_DOWN');
}
}
}
}
// add a listener on load
window.addEventListener("load", function(event) {
const dispatcher = new SwipeEventDispatcher(document.body);
dispatcher.on('SWIPE_RIGHT', () => { console.log('I swiped right!') })
dispatcher.on('SWIPE_LEFT', () => { console.log('I swiped left!') })
});
If you are in SQL*Plus or SQL Developer, you want to run
SQL> set define off;
before executing the SQL statement. That turns off the checking for substitution variables.
SET directives like this are instructions for the client tool (SQL*Plus or SQL Developer). They have session scope, so you would have to issue the directive every time you connect (you can put the directive in your client machine's glogin.sql if you want to change the default to have DEFINE set to OFF). There is no risk that you would impact any other user or session in the database.
Disclaimer: While the top answer is probably a better solution, as a beginner it's a lot to take in when all you want is something very simple. This is intended as a more direct answer to your original question "How can I select certain elements in React"
I think the confusion in your question is because you have React components which you are being passed the id "Progress1", "Progress2" etc. I believe this is not setting the html attribute 'id', but the React component property. e.g.
class ProgressBar extends React.Component {
constructor(props) {
super(props)
this.state = {
id: this.props.id <--- ID set from <ProgressBar id="Progress1"/>
}
}
}
As mentioned in some of the answers above you absolutely can use document.querySelector
inside of your React app, but you have to be clear that it is selecting the html output of your components' render methods. So assuming your render output looks like this:
render () {
const id = this.state.id
return (<div id={"progress-bar-" + id}></div>)
}
Then you can elsewhere do a normal javascript querySelector call like this:
let element = document.querySelector('#progress-bar-Progress1')
I have Test your code, this error shows when you already have the DB imported or with some tables with the same name, also the Array error that shows is because you add in in the exec parenthesis, here is the fixed version:
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlDatabaseName ='test';
$mysqlUserName ='root';
$mysqlPassword ='';
$mysqlHostName ='localhost';
$mysqlImportFilename ='dbbackupmember.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;
$output=array();
exec($command,$output,$worked);
switch($worked){
case 0:
echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>';
break;
case 1:
echo 'There was an error during import.';
break;
}
?>
You can print Unicode objects as well, you don't need to do str() around it.
Assuming you really want a str:
When you do str(u'\u2013') you are trying to convert the Unicode string to a 8-bit string. To do this you need to use an encoding, a mapping between Unicode data to 8-bit data. What str() does is that is uses the system default encoding, which under Python 2 is ASCII. ASCII contains only the 127 first code points of Unicode, that is \u0000 to \u007F1. The result is that you get the above error, the ASCII codec just doesn't know what \u2013 is (it's a long dash, btw).
You therefore need to specify which encoding you want to use. Common ones are ISO-8859-1, most commonly known as Latin-1, which contains the 256 first code points; UTF-8, which can encode all code-points by using variable length encoding, CP1252 that is common on Windows, and various Chinese and Japanese encodings.
You use them like this:
u'\u2013'.encode('utf8')
The result is a str containing a sequence of bytes that is the uTF8 representation of the character in question:
'\xe2\x80\x93'
And you can print it:
>>> print '\xe2\x80\x93'
–
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
Using the same method for iterating through both arrays and hashes makes sense, for example to process nested hash-and-array structures often resulting from parsers, from reading JSON files etc..
One clever way that has not yet been mentioned is how it's done in the Ruby Facets library of standard library extensions. From here:
class Array
# Iterate over index and value. The intention of this
# method is to provide polymorphism with Hash.
#
def each_pair #:yield:
each_with_index {|e, i| yield(i,e) }
end
end
There is already Hash#each_pair
, an alias of Hash#each
. So after this patch, we also have Array#each_pair
and can use it interchangeably to iterate through both Hashes and Arrays. This fixes the OP's observed insanity that Array#each_with_index
has the block arguments reversed compared to Hash#each
. Example usage:
my_array = ['Hello', 'World', '!']
my_array.each_pair { |key, value| pp "#{key}, #{value}" }
# result:
"0, Hello"
"1, World"
"2, !"
my_hash = { '0' => 'Hello', '1' => 'World', '2' => '!' }
my_hash.each_pair { |key, value| pp "#{key}, #{value}" }
# result:
"0, Hello"
"1, World"
"2, !"
// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);
// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself
// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);
Just set the backdrop
property to 'static'
.
$('#myModal').modal({
backdrop: 'static',
keyboard: true
})
You may also want to set the keyboard
property to false
because that prevents the modal from being closed by pressing the Esc key on the keyboard.
$('#myModal').modal({
backdrop: 'static',
keyboard: false
})
myModal
is the ID of the div that contains your modal content.
That works fine with font icons like 's7 stroke icons' and 'font-awesome':
.mirror {
display: inline-block;
transform: scaleX(-1);
}
And then on target element:
<button>
<span class="s7-back mirror"></span>
<span>Next</span>
</button>
GitHub has a new option relative to the preceding answers, just copy/paste the command lines from the PR:
Merge
or Squash and merge
buttonview command line instructions
Use these simple steps to resize the vmdk
File -> Virtual Media Player
properties
Here you can increase or decrease the vdi size.
My error occurred because, somehow, there was an obj folder created inside my controllers folder. Just do a search in your application for a line inside your Assemblyinfo.cs. There may be a duplicate somewhere.
Try this one. Its working for me in 3tier Architecture Web Application.
"'" + DateTime.Now.ToString() + "'"
Please remember the Single Quotes in the insert Query.
For example:
string Command = @"Insert Into CONFIG_USERS(smallint_empID,smallint_userID,str_username,str_pwd,str_secquestion,str_secanswer,tinyint_roleID,str_phone,str_email,Dt_createdOn,Dt_modifiedOn) values ("
+ u.Employees + ","
+ u.UserID + ",'"
+ u.Username + "','"
+ u.GetPassword() + "','"
+ u.SecQ + "','"
+ u.SecA + "',"
+ u.RoleID + ",'"
+ u.Phone + "','"
+ u.Email + "','"
+ DateTime.Now.ToString() + "','"
+ DateTime.Now.ToString() + "')";
The DateTime
insertion at the end of the line.
Simple Example:
func method(arg: Bool, completion: (Bool) -> ()) {
print("First line of code executed")
// do stuff here to determine what you want to "send back".
// we are just sending the Boolean value that was sent in "back"
completion(arg)
}
How to use it:
method(arg: true, completion: { (success) -> Void in
print("Second line of code executed")
if success { // this will be equal to whatever value is set in this method call
print("true")
} else {
print("false")
}
})
Change your TableView Style:
self.tableview = [[UITableView alloc] initwithFrame:frame style:UITableViewStyleGrouped];
As per apple documentation for UITableView:
UITableViewStylePlain- A plain table view. Any section headers or footers are displayed as inline separators and float when the table view is scrolled.
UITableViewStyleGrouped- A table view whose sections present distinct groups of rows. The section headers and footers do not float.
Hope this small change will help you ..
OK, this approach will only be useful when you are connecting to a real device rather than to an Android emulator.
Resetting the DDMS ADB connection timeout won't work nicely with a real device when there is a problem with USB debugging mode of the device.
So, disabling and re-enabling USB debugging mode seems to resolve the issue by creating a new fresh ADB session on the device.
This fixes UTF-8 printing in python:
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
Use window.open()
:
var win = window.open('http://stackoverflow.com/', '_blank');
if (win) {
//Browser has allowed it to be opened
win.focus();
} else {
//Browser has blocked it
alert('Please allow popups for this website');
}
Depending on the browsers implementation this will work
There is nothing you can do to make it open in a window rather than a tab.
Swift version:
extension UITextField {
@IBInspectable var padding_left: CGFloat {
get {
LF.log("WARNING no getter for UITextField.padding_left")
return 0
}
set (f) {
layer.sublayerTransform = CATransform3DMakeTranslation(f, 0, 0)
}
}
}
So that you can assign value in IB
OR operator:
<div ng-repeat="k in items">
<div ng-if="k || 'a' or k == 'b'">
<!-- SOME CONTENT -->
</div>
</div>
Even though it is simple enough to read, I hope as a developer you are use better names than 'a' 'k' 'b' etc..
For Example:
<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
<li ng-if="user.groups.admin || group.title == 'Home Pages'">
<!--Content-->
</li>
</div>
Another OR example
<p ng-if="group.title != 'Dispatcher News' or group.title != 'Coordinator News'" style="padding: 5px;">No links in group.</p>
AND operator (For those stumbling across this stackoverflow answer looking for an AND instead of OR condition)
<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
<li ng-if="user.groups.admin && group.title == 'Home Pages'">
<!--Content-->
</li>
</div>
Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.
Javascript code embedded aswell:
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 1,
center: new google.maps.LatLng(0, 0),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
});
});
}
});
When I was beginner at Android studio ,this was general issue I face through . Generally the problem arises when the R.java files during conversion of hex code properly donot recognize the appropriate magic number . So we should kept in mind that all the XML files are properly wriiten.This is oftenly arises due to problem in XML files . Go in each XML files n be sure all the files are true means valid . Then go to File and synchronize the project .My error remove many times by such steps .
create or replace procedure mili(num in number)
as
yr number;
yrsms number;
mon number;
monsms number;
wk number;
wksms number;
dy number;
dysms number;
hr number;
hrsms number;
mn number;
mnsms number;
sec number;
begin
yr := FLOOR(num/31556952000);
yrsms := mod(num, 31556952000);
mon := FLOOR(yrsms/2629746000);
monsms := mod(num,2629746000);
wk := FLOOR(monsms/(604800000));
wksms := mod(num,604800000);
dy := floor(wksms/ (24*60*60*1000));
dysms :=mod(num,24*60*60*1000);
hr := floor((dysms)/(60*60*1000));
hrsms := mod(num,60*60*1000);
mn := floor((hrsms)/(60*1000));
mnsms := mod(num,60*1000);
sec := floor((mnsms)/(1000));
dbms_output.put_line(' Year:'||yr||' Month:'||mon||' Week:'||wk||' Day:'||dy||' Hour:'||hr||' Min:'||mn||' Sec: '||sec);
end;
/
begin
mili(12345678904234);
end;
Try this
var url = ApiUrl(`/customers`);
if(data){
url += '?search='+data;
}
else
{
url += `?page=${page}&per_page=${perpage}`;
}
console.log(url);
I got a working solulion using the answers from @John and @Arpad link and @RobWinch link
I use Spring Security 3.2.9 and jQuery 1.10.2.
Extend Spring's class to cause 4XX response only from AJAX requests:
public class CustomLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
public CustomLoginUrlAuthenticationEntryPoint(final String loginFormUrl) {
super(loginFormUrl);
}
// For AJAX requests for user that isn't logged in, need to return 403 status.
// For normal requests, Spring does a (302) redirect to login.jsp which the browser handles normally.
@Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException)
throws IOException, ServletException {
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
} else {
super.commence(request, response, authException);
}
}
}
applicationContext-security.xml
<security:http auto-config="false" use-expressions="true" entry-point-ref="customAuthEntryPoint" >
<security:form-login login-page='/login.jsp' default-target-url='/index.jsp'
authentication-failure-url="/login.jsp?error=true"
/>
<security:access-denied-handler error-page="/errorPage.jsp"/>
<security:logout logout-success-url="/login.jsp?logout" />
...
<bean id="customAuthEntryPoint" class="com.myapp.utils.CustomLoginUrlAuthenticationEntryPoint" scope="singleton">
<constructor-arg value="/login.jsp" />
</bean>
...
<bean id="requestCache" class="org.springframework.security.web.savedrequest.HttpSessionRequestCache">
<property name="requestMatcher">
<bean class="org.springframework.security.web.util.matcher.NegatedRequestMatcher">
<constructor-arg>
<bean class="org.springframework.security.web.util.matcher.MediaTypeRequestMatcher">
<constructor-arg>
<bean class="org.springframework.web.accept.HeaderContentNegotiationStrategy"/>
</constructor-arg>
<constructor-arg value="#{T(org.springframework.http.MediaType).APPLICATION_JSON}"/>
<property name="useEquals" value="true"/>
</bean>
</constructor-arg>
</bean>
</property>
</bean>
In my JSPs, add a global AJAX error handler as shown here
$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
if ( jqxhr.status === 403 ) {
window.location = "login.jsp";
} else {
if(thrownError != null) {
alert(thrownError);
} else {
alert("error");
}
}
});
Also, remove existing error handlers from AJAX calls in JSP pages:
var str = $("#viewForm").serialize();
$.ajax({
url: "get_mongoDB_doc_versions.do",
type: "post",
data: str,
cache: false,
async: false,
dataType: "json",
success: function(data) { ... },
// error: function (jqXHR, textStatus, errorStr) {
// if(textStatus != null)
// alert(textStatus);
// else if(errorStr != null)
// alert(errorStr);
// else
// alert("error");
// }
});
I hope it helps others.
Update1 I found that I needed to add the option (always-use-default-target="true") to the form-login config. This was needed since after an AJAX request gets redirected to the login page (due to expired session), Spring remembers the previous AJAX request and auto redirects to it after login. This causes the returned JSON to be displayed on the browser page. Of course, not what I want.
Update2
Instead of using always-use-default-target="true"
, use @RobWinch example of blocking AJAX requests from the requstCache. This allows normal links to be redirected to their original target after login, but AJAX go to the home page after login.
If [John Smith]
is in cell A1, then use this formula to do what you want:
=SUBSTITUTE(SUBSTITUTE(A1, "[", ""), "]", "")
The inner SUBSTITUTE replaces all instances of "[" with "" and returns a new string, then the other SUBSTITUTE replaces all instances of "]" with "" and returns the final result.
Here is a simple and clean solution without using JavaScript or table layout hacks. It is similar to this answer: Input text auto width filling 100% with other elements floating
It is important to wrap the input field with a span which is display:block
. Next thing is that the button has to come first and the the input field second.
Then you can float the button to the right and the input field fills the remaining space.
form {_x000D_
width: 500px;_x000D_
overflow: hidden;_x000D_
background-color: yellow;_x000D_
}_x000D_
input {_x000D_
width: 100%;_x000D_
}_x000D_
span {_x000D_
display: block;_x000D_
overflow: hidden;_x000D_
padding-right:10px;_x000D_
}_x000D_
button {_x000D_
float: right;_x000D_
}
_x000D_
<form method="post">_x000D_
<button>Search</button>_x000D_
<span><input type="text" title="Search" /></span>_x000D_
</form>
_x000D_
A simple fiddle: http://jsfiddle.net/v7YTT/90/
Update 1: If your website is targeted towards modern browsers only, I suggest using flexible boxes. Here you can see the current support.
Update 2: This even works with multiple buttons or other elements that share the full with with the input field. Here is an example.
From RFC 6750, Section 1.2:
Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).
The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.
The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.
See also: Mozilla MDN Header Information.
This is a circular dependency issue. Golang programs must be acyclic. In Golang cyclic imports are not allowed (That is its import graph must not contain any loops)
Lets say your project go-circular-dependency
have 2 packages "package one" & it has "one.go" & "package two" & it has "two.go" So your project structure is as follows
+--go-circular-dependency
+--one
+-one.go
+--two
+-two.go
This issue occurs when you try to do something like following.
Step 1 - In one.go
you import package two
(Following is one.go
)
package one
import (
"go-circular-dependency/two"
)
//AddOne is
func AddOne() int {
a := two.Multiplier()
return a + 1
}
Step 2 - In two.go
you import package one
(Following is two.go
)
package two
import (
"fmt"
"go-circular-dependency/one"
)
//Multiplier is going to be used in package one
func Multiplier() int {
return 2
}
//Total is
func Total() {
//import AddOne from "package one"
x := one.AddOne()
fmt.Println(x)
}
In Step 2, you will receive an error "can't load package: import cycle not allowed" (This is called "Circular Dependency" error)
Technically speaking this is bad design decision and you should avoid this as much as possible, but you can "Break Circular Dependencies via implicit interfaces" (I personally don't recommend, and highly discourage this practise, because by design Go programs must be acyclic)
Try to keep your import dependency shallow. When the dependency graph becomes deeper (i.e package x imports y, y imports z, z imports x) then circular dependencies become more likely.
Sometimes code repetition is not bad idea, which is exactly opposite of DRY (don't repeat yourself)
So in Step 2 that is in two.go
you should not import package one. Instead in two.go
you should actually replicate the functionality of AddOne()
written in one.go
as follows.
package two
import (
"fmt"
)
//Multiplier is going to be used in package one
func Multiplier() int {
return 2
}
//Total is
func Total() {
// x := one.AddOne()
x := Multiplier() + 1
fmt.Println(x)
}
If you just want the unix timestamp, create an extension:
extension Date {
func currentTimeMillis() -> Int64 {
return Int64(self.timeIntervalSince1970 * 1000)
}
}
Then you can use it just like in other programming languages:
let timestamp = Date().currentTimeMillis()
Just throw some light in to some issues related to this control.
Date picker is not a standard control that comes with office package. So developers encountered issues like missing date picker controls when application deployed in some other machiens/versions of office. In order to use it you have to activate the reference to the .dll, .ocx file that contains it.
In the event of a missing date picker, you have to replace MSCOMCT2.OCX file in System or System32 directory and register it properly. Try this link to do the proper replacement of the file.
In the VBA editor menu bar-> select tools-> references and then find the date picker reference and check it.
If you need the file, download MSCOMCT2.OCX from here.
You should use modules, see http://modules.sourceforge.net/
EDIT: The modules package has not been updated since 2012 but still works ok for the basics. All the new features, bells and whistles happen in lmod this day (which I like it more): https://www.tacc.utexas.edu/research-development/tacc-projects/lmod
Three important steps - How to Task Schedule an excel.xls(m) file
simply:
IN MORE DETAIL...
`
' a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt to .vbs
'Write Excel.xls Sheet's full path here
strPath = "C:\RodsData.xlsm"
'Write the macro name - could try including module name
strMacro = "Update" ' "Sheet1.Macro2"
'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application")
objApp.Visible = True ' or False
'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath)
objApp.Run strMacro ' wbToRun.Name & "!" & strMacro
wbToRun.Save
wbToRun.Close
objApp.Quit
'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!", vbInformation
'
`
set Program/script: = C:\Windows\System32\cscript.exe
set Add arguments (optional): = C:\MyVbsFile.vbs
That should work.
Let me know!
Rod Bowen
You could use row_factory, as in the example in the docs:
import sqlite3
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]
or follow the advice that's given right after this example in the docs:
If returning a tuple doesn’t suffice and you want name-based access to columns, you should consider setting row_factory to the highly-optimized sqlite3.Row type. Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution.
I love how easy this is in Android Studio.
In Android Studio go to File > Settings > Version Control > GitHub. Then enter your GitHub username and password. (You only have to do this step once. For future projects you can skip it.)
With your Android Studio project open, go to VCS > Import into Version Control > Share Project on GitHub.
Then click Share and OK.
That's all!
Add <b>
tag
<p> <b> I am in Bold </b></p>
For more text formatting tags click here
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
Most windows users won't have that font on their computers. Also, you can't just submit it to your server and call it using font-face because this isn't a free font...
And last, but not least, answering the question that nobody mentioned yet, Helvetica and Helvetica Neue do not render well on screen unless they have a really big font-size
. You'll find a lot of pages using this font, and in all of them you'll see that the top border of a line of text looks wavy and that some letters look taller than others. In my opinion this is the main reason why you shouldn't use it. There are other options for you to use, like Open Sans.
With Java 6 form I think is better to check it is closed or not before close (for example if some connection pooler evict the connection in other thread) - for example some network problem - the statement and resultset state can be come closed. (it is not often happens, but I had this problem with Oracle and DBCP). My pattern is for that (in older Java syntax) is:
try {
//...
return resp;
} finally {
if (rs != null && !rs.isClosed()) {
try {
rs.close();
} catch (Exception e2) {
log.warn("Cannot close resultset: " + e2.getMessage());
}
}
if (stmt != null && !stmt.isClosed()) {
try {
stmt.close();
} catch (Exception e2) {
log.warn("Cannot close statement " + e2.getMessage());
}
}
if (con != null && !conn.isClosed()) {
try {
con.close();
} catch (Exception e2) {
log.warn("Cannot close connection: " + e2.getMessage());
}
}
}
In theory it is not 100% perfect because between the the checking the close state and the close itself there is a little room for the change for state. In the worst case you will get a warning in long. - but it is lesser than the possibility of state change in long run queries. We are using this pattern in production with an "avarage" load (150 simultanous user) and we had no problem with it - so never see that warning message.
->getSingleScalarResult() will return a single value, instead of an array.
The solutions that involve setting this.state
directly aren't working for me in React 16, so here is what I did to reset each key:
const initialState = { example: 'example' }
...
constructor() {
super()
this.state = initialState
}
...
reset() {
const keys = Object.keys(this.state)
const stateReset = keys.reduce((acc, v) => ({ ...acc, [v]: undefined }), {})
this.setState({ ...stateReset, ...initialState })
}
I needed to do the following...
def delete_bucket
s3 = init_amazon_s3
s3.buckets['BUCKET-NAME'].objects.each do |obj|
obj.delete
end
end
def init_amazon_s3
config = YAML.load_file("#{Rails.root}/config/s3.yml")
AWS.config(:access_key_id => config['access_key_id'],:secret_access_key => config['secret_access_key'])
s3 = AWS::S3.new
end
Add height & width properties to your .css file.
^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$
I know I'm a little late, but something I found that works (and doesn't require using csv
) is to write a for loop that writes to your file for every element in your list.
# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']
# Open File
resultFyle = open("output.csv",'w')
# Write data to file
for r in RESULTS:
resultFyle.write(r + "\n")
resultFyle.close()
I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.
Modified versions of http://www.peterbe.com/plog/uniqifiers-benchmark
To preserve the order:
def f(seq): # Order preserving
''' Modified version of Dave Kirby solution '''
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)]
OK, now how does it work, because it's a little bit tricky here if x not in seen and not seen.add(x)
:
In [1]: 0 not in [1,2,3] and not print('add')
add
Out[1]: True
Why does it return True? print (and set.add) returns nothing:
In [3]: type(seen.add(10))
Out[3]: <type 'NoneType'>
and not None == True
, but:
In [2]: 1 not in [1,2,3] and not print('add')
Out[2]: False
Why does it print 'add' in [1] but not in [2]? See False and print('add')
, and doesn't check the second argument, because it already knows the answer, and returns true only if both arguments are True.
More generic version, more readable, generator based, adds the ability to transform values with a function:
def f(seq, idfun=None): # Order preserving
return list(_f(seq, idfun))
def _f(seq, idfun=None):
''' Originally proposed by Andrew Dalke '''
seen = set()
if idfun is None:
for x in seq:
if x not in seen:
seen.add(x)
yield x
else:
for x in seq:
x = idfun(x)
if x not in seen:
seen.add(x)
yield x
Without order (it's faster):
def f(seq): # Not order preserving
return list(set(seq))
I've faced this issue today. I am using Centos7, the solution was to install tomcat-admin-webapp package.
yum install tomcat-webapps tomcat-admin-webapps
Close the file e:\gestion\yourfile.dat
, open by any user (/a *
)
openfiles /disconnect /a * /op "e:\gestion\yourfile.dat"
In essence its job is very similar to IEnumerable<T>
- to represent a queryable data source - the difference being that the various LINQ methods (on Queryable
) can be more specific, to build the query using Expression
trees rather than delegates (which is what Enumerable
uses).
The expression trees can be inspected by your chosen LINQ provider and turned into an actual query - although that is a black art in itself.
This is really down to the ElementType
, Expression
and Provider
- but in reality you rarely need to care about this as a user. Only a LINQ implementer needs to know the gory details.
Re comments; I'm not quite sure what you want by way of example, but consider LINQ-to-SQL; the central object here is a DataContext
, which represents our database-wrapper. This typically has a property per table (for example, Customers
), and a table implements IQueryable<Customer>
. But we don't use that much directly; consider:
using(var ctx = new MyDataContext()) {
var qry = from cust in ctx.Customers
where cust.Region == "North"
select new { cust.Id, cust.Name };
foreach(var row in qry) {
Console.WriteLine("{0}: {1}", row.Id, row.Name);
}
}
this becomes (by the C# compiler):
var qry = ctx.Customers.Where(cust => cust.Region == "North")
.Select(cust => new { cust.Id, cust.Name });
which is again interpreted (by the C# compiler) as:
var qry = Queryable.Select(
Queryable.Where(
ctx.Customers,
cust => cust.Region == "North"),
cust => new { cust.Id, cust.Name });
Importantly, the static methods on Queryable
take expression trees, which - rather than regular IL, get compiled to an object model. For example - just looking at the "Where", this gives us something comparable to:
var cust = Expression.Parameter(typeof(Customer), "cust");
var lambda = Expression.Lambda<Func<Customer,bool>>(
Expression.Equal(
Expression.Property(cust, "Region"),
Expression.Constant("North")
), cust);
... Queryable.Where(ctx.Customers, lambda) ...
Didn't the compiler do a lot for us? This object model can be torn apart, inspected for what it means, and put back together again by the TSQL generator - giving something like:
SELECT c.Id, c.Name
FROM [dbo].[Customer] c
WHERE c.Region = 'North'
(the string might end up as a parameter; I can't remember)
None of this would be possible if we had just used a delegate. And this is the point of Queryable
/ IQueryable<T>
: it provides the entry-point for using expression trees.
All this is very complex, so it is a good job that the compiler makes it nice and easy for us.
For more information, look at "C# in Depth" or "LINQ in Action", both of which provide coverage of these topics.
An answer that I've been using that has been working for me quite well that I didn't already see here (this question is very old, so it may have not worked then) is actually
SELECT t.phone,
t.phone2
FROM jewishyellow.users t
WHERE t.phone LIKE '813%'
AND t.phone2 > ''
Notice the > ''
part, which will check if the value is not null, and if the value isn't just whitespace or blank.
Basically, if the field has something in it other than whitespace or NULL
, it is true. It's also super short, so it's easy to write, and another plus over the COALESCE()
and IFNULL()
functions is that this is index friendly, since you're not comparing the output of a function on a field to anything.
Test cases:
SELECT if(NULL > '','true','false');-- false
SELECT if('' > '','true','false');-- false
SELECT if(' ' > '','true','false');-- false
SELECT if('\n' > '','true','false');-- false
SELECT if('\t' > '','true','false');-- false
SELECT if('Yeet' > '','true','false');-- true
UPDATE There is a caveat to this that I didn't expect, but numerical values that are zero or below are not greater than a blank string, so if you're dealing with numbers that can be zero or negative then DO NOT DO THIS, it bit me very recently and was very difficult to debug :(
If you're using strings (char, varchar, text, etc.), then this will be perfectly be fine, just be careful with numerics.
for multiple dropdowns
$('[id^=RBLExperienceApplicable][value='+ SelectedVAlue +']').attr("checked","checked");
here RBLExperienceApplicable
is the matching part of the radio button groups input tag ids.
and [id^=RBLExperienceApplicable]
matches all the radio button whose id start with RBLExperienceApplicable
Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule
.
Therefore, before starting '$ sqlplus' on OS, run the followings:
On Windows
set NLS_LANG=AMERICAN_AMERICA.UTF8
On Unix (Solaris and Linux, centos etc)
export NLS_LANG=AMERICAN_AMERICA.UTF8
It would also be advisable to set env variable in your '.bash_profile' [on start up script]
This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.
just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.
This error also happens if you have got the order of your components wrong.
Example: this wrong:
<ComponentA>
<ComponentB>
</ComponentA>
</ComponentB>
correct way:
<ComponentA>
<ComponentB>
</ComponentB>
</ComponentA>
This should work for everyone, any screen resolutions:
.modal-body {
max-height: calc(100vh - 143px);
overflow-y: auto; }
First, count your modal header and footer height, in my case I have H4
heading so I have them on 141px
, already counted default modal margin in 20px(top+bottom)
.
So that subtract 141px
is the max-height
for my modal height, for the better result there are both border top and bottom by 1px
, for this, 143px
will work perfectly.
In some case of styling you may like to use overflow-y: auto;
instead of overflow-y: scroll;
, try it.
Try it, and you get the best result in both computer or mobile devices.
If you have a heading larger than H4
, recount it see how much px
you would like to subtract.
If you don't know what I am telling, just change the number of 143px
, see what is the best result for your case.
Last, I'd suggest have it an inline CSS.
Universal extension method for DataTable. May be somebody be interesting. Idea creating dynamic properties I take from another post: https://stackoverflow.com/a/15819760/8105226
public static IEnumerable<dynamic> AsEnumerable(this DataTable dt)
{
List<dynamic> result = new List<dynamic>();
Dictionary<string, object> d;
foreach (DataRow dr in dt.Rows)
{
d = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
d.Add(dc.ColumnName, dr[dc]);
result.Add(GetDynamicObject(d));
}
return result.AsEnumerable<dynamic>();
}
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
If you want to rename a branch while pointed to any branch, do:
git branch -m <oldname> <newname>
If you want to rename the current branch, you can do:
git branch -m <newname>
A way to remember this is -m
is for "move" (or mv
), which is how you rename files. Adding an alias could also help. To do so, run the following:
git config --global alias.rename 'branch -m'
If you are on Windows or another case-insensitive filesystem, and there are only capitalization changes in the name, you need to use -M
, otherwise, git will throw branch already exists error:
git branch -M <newname>
This has been here quite a while but posting this. Might be useful for someone.
@RequestMapping( "/{id}/**" )
public void foo( @PathVariable String id, HttpServletRequest request ) {
String urlTail = new AntPathMatcher()
.extractPathWithinPattern( "/{id}/**", request.getRequestURI() );
}
<input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57" ondragstart="return false;" ondrop="return false;">
Input filed only accept numbers, But it's temporary fix only.
You seem to want to use a CURSOR
. Though most of the times it's best to use a set based solution, there are some times where a CURSOR
is the best solution. Without knowing more about your real problem, we can't help you more than that:
DECLARE @PractitionerId int
DECLARE MY_CURSOR CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT DISTINCT PractitionerId
FROM Practitioner
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @PractitionerId
WHILE @@FETCH_STATUS = 0
BEGIN
--Do something with Id here
PRINT @PractitionerId
FETCH NEXT FROM MY_CURSOR INTO @PractitionerId
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
I'd do this:
add the dependency as you like in your pom:
<dependency>
<groupId>com.stackoverflow...</groupId>
<artifactId>artifactId...</artifactId>
<version>1.0</version>
</dependency>
run mvn install
it will try to download the jar and fail. On the process, it
will give you the complete command of installing the jar with the error message. Copy that command and run it! easy huh?!
Docker Compose has been updated. They now have a version 2 file format.
Version 2 files are supported by Compose 1.6.0+ and require a Docker Engine of version 1.10.0+.
They now support the networking feature of Docker which when run sets up a default network called myapp_default
From their documentation your file would look something like the below:
version: '2'
services:
web:
build: .
ports:
- "8000:8000"
fpm:
image: phpfpm
nginx
image: nginx
As these containers are automatically added to the default myapp_default network they would be able to talk to each other. You would then have in the Nginx config:
fastcgi_pass fpm:9000;
Also as mentioned by @treeface in the comments remember to ensure PHP-FPM is listening on port 9000, this can be done by editing /etc/php5/fpm/pool.d/www.conf
where you will need listen = 9000
.
I have kept the below here for those using older version of Docker/Docker compose and would like the information.
I kept stumbling upon this question on google when trying to find an answer to this question but it was not quite what I was looking for due to the Q/A emphasis on docker-compose (which at the time of writing only has experimental support for docker networking features). So here is my take on what I have learnt.
Docker has recently deprecated its link feature in favour of its networks feature
Therefore using the Docker Networks feature you can link containers by following these steps. For full explanations on options read up on the docs linked previously.
First create your network
docker network create --driver bridge mynetwork
Next run your PHP-FPM container ensuring you open up port 9000 and assign to your new network (mynetwork
).
docker run -d -p 9000 --net mynetwork --name php-fpm php:fpm
The important bit here is the --name php-fpm
at the end of the command which is the name, we will need this later.
Next run your Nginx container again assign to the network you created.
docker run --net mynetwork --name nginx -d -p 80:80 nginx:latest
For the PHP and Nginx containers you can also add in --volumes-from
commands etc as required.
Now comes the Nginx configuration. Which should look something similar to this:
server {
listen 80;
server_name localhost;
root /path/to/my/webroot;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php-fpm:9000;
fastcgi_index index.php;
include fastcgi_params;
}
}
Notice the fastcgi_pass php-fpm:9000;
in the location block. Thats saying contact container php-fpm
on port 9000
. When you add containers to a Docker bridge network they all automatically get a hosts file update which puts in their container name against their IP address. So when Nginx sees that it will know to contact the PHP-FPM container you named php-fpm
earlier and assigned to your mynetwork
Docker network.
You can add that Nginx config either during the build process of your Docker container or afterwards its up to you.
like this:
/\<word\>
\<
means beginning of a word, and \>
means the end of a word,
Adding @Roe's comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*'
to search forward in the file or '#'
to search backwards.
Do nothing to the browser. CORS is supported by default on all modern browsers (and since Firefox 3.5).
The server being accessed by JavaScript has to give the site hosting the HTML document in which the JS is running permission via CORS HTTP response headers.
security.fileuri.strict_origin_policy
is used to give JS in local HTML documents access to your entire hard disk. Don't set it to false
as it makes you vulnerable to attacks from downloaded HTML documents (including email attachments).
Get-WmiObject Win32_Processor | Select LoadPercentage | Format-List
This gives you CPU load.
Get-WmiObject Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select Average
Both of the following code will work fine for removing highchart.com from the chart:-
credits: false
or
credits:{
enabled:false,
}
Taken from: http://developer.android.com/guide/topics/ui/ui-events.html
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
protected void onCreate(Bundle savedValues) {
...
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
...
}
.wrapper{
float: left;
width: 100%;
text-align: center;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.button{
display:inline-block;
}
<div class="wrapper">
<button class="button">Button1</button>
<button class="button">Button2</button>
</div>
From Python 3 documentation (the same holds for python 2.7):
Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.
in python 2.7:
>>> my_set = {'foo', 'bar', 'baz', 'baz', 'foo'}
>>> my_set
set(['bar', 'foo', 'baz'])
Be aware that {}
is also used for map
/dict
:
>>> m = {'a':2,3:'d'}
>>> m[3]
'd'
>>> m={}
>>> type(m)
<type 'dict'>
One can also use comprehensive syntax to initialize sets:
>>> a = {x for x in """didn't know about {} and sets """ if x not in 'set' }
>>> a
set(['a', ' ', 'b', 'd', "'", 'i', 'k', 'o', 'n', 'u', 'w', '{', '}'])
The condition i==j+1
will not be true for i==2
. This can be fixed by a couple of changes to the inner loop:
#include <stdio.h>
int main(void)
{
for (int i=2; i<100; i++)
{
for (int j=2; j<=i; j++) // Changed upper bound
{
if (i == j) // Changed condition and reversed order of if:s
printf("%d\n",i);
else if (i%j == 0)
break;
}
}
}
We can schedule the timer to do the work.After the end of the time we set the message won't send.
This is the code.
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//here you can write the code for send the message
}
}, 10, 60000);
In here the method we are calling is,
public void scheduleAtFixedRate (TimerTask task, long delay, long period)
In here,
task : the task to schedule
delay: amount of time in milliseconds before first execution.
period: amount of time in milliseconds between subsequent executions.
For more information you can refer: Android Developer
You can stop the timer by calling,
timer.cancel();
In addition to adding python's bin
directory to $PATH
variable, I also had to change the owner of that directory, to make it work. No idea why I wasn't the owner already.
chown -R ~/Library/Python/
Just to correct mingos' answer:
If you set the expiration time to 0, the cookie won't be created at all. I've tested this on Google Chrome at least, and when set to 0 that was the result. The cookie, I guess, expires immediately after creation.
To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether.
Example:
Instead of:
document.cookie = "cookie_name=cookie_value; 0; path=/";
Just write:
document.cookie = "cookie_name=cookie_value; path=/";
<VirtualHost *:80>
DocumentRoot /var/www/app1
ServerName app1.example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/example
ServerName example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/wildcard
ServerName other.example.com
ServerAlias *.example.com
</VirtualHost>
Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.
In my case I was committing transaction when persist method was used. On changing persist to save method , it got resolved.
Here it is in Python with, basically, string comparisons and a state machine.
def divide_by_3(input):
to_do = {}
enque_index = 0
zero_to_9 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
leave_over = 0
for left_over in (0, 1, 2):
for digit in zero_to_9:
# left_over, digit => enque, leave_over
to_do[(left_over, digit)] = (zero_to_9[enque_index], leave_over)
if leave_over == 0:
leave_over = 1
elif leave_over == 1:
leave_over = 2
elif leave_over == 2 and enque_index != 9:
leave_over = 0
enque_index = (1, 2, 3, 4, 5, 6, 7, 8, 9)[enque_index]
answer_q = []
left_over = 0
digits = list(str(input))
if digits[0] == "-":
answer_q.append("-")
digits = digits[1:]
for digit in digits:
enque, left_over = to_do[(left_over, int(digit))]
if enque or len(answer_q):
answer_q.append(enque)
answer = 0
if len(answer_q):
answer = int("".join([str(a) for a in answer_q]))
return answer
Swift 3 solution with iOS 9 'NSBatchDeleteRequest' and fallback to earlier iOS versions implemented as an extension on 'NSManagedObjectContext'. Apple reference https://developer.apple.com/library/content/featuredarticles/CoreData_Batch_Guide/BatchDeletes/BatchDeletes.html
extension NSManagedObjectContext {
func batchDeleteEntities<T: NSManagedObject>(ofType type: T.Type) throws {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: type.self))
if #available(iOS 9.0, *) {
let request = NSBatchDeleteRequest(fetchRequest: fetchRequest)
let result = try execute(request) as? NSBatchDeleteResult
if let objectIDArray = result?.result as? [NSManagedObjectID] {
let changes = [NSDeletedObjectsKey: objectIDArray]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [self])
}
} else {
fetchRequest.includesPropertyValues = false
let results = try fetch(fetchRequest)
if let actualResults = results as? [NSManagedObject], !actualResults.isEmpty {
actualResults.forEach { delete($0) }
}
}
}
}
Building on the answer from @Brian-Fisher and answering the comments of some of the people on this post, I have a bunch of huge (and unnecessary) tables in my database so I wanted to skip their contents when copying, but keep the structure:
mysqldump -h <host> -u <username> -p <schema> --no-data > db-structure.sql
mysqldump -h <host> -u <username> -p <schema> --no-create-info --ignore-table=schema.table1 --ignore-table=schema.table2 > db-data.sql
The resulting two files are structurally sound but the dumped data is now ~500MB rather than 9GB, much better for me. I can now import these two files into another database for testing purposes without having to worry about manipulating 9GB of data or running out of disk space.
I've used this directive with success before:
.directive('sameAs', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (viewValue === scope[attrs.sameAs]) {
ctrl.$setValidity('sameAs', true);
return viewValue;
} else {
ctrl.$setValidity('sameAs', false);
return undefined;
}
});
}
};
});
<input ... name="password" />
<input type="password" placeholder="Confirm Password"
name="password2" ng-model="password2" ng-minlength="9" same-as='password' required>
I'd strongly recommend using a CG HSVtoRGB shader function, they are awesome... it gives you natural color control like a painter instead of control like a crt monitor, which you arent presumably!
This is a way to make 1 float value. i.e. Grey, into 1000 ds of combinations of color and brightness and saturation etc:
int rand = a global color randomizer that you can control by script/ by a crossfader etc.
float h = perlin(grey,23.3*rand)
float s = perlin(grey,54,4*rand)
float v = perlin(grey,12.6*rand)
Return float4 HSVtoRGB(h,s,v);
result is AWESOME COLOR RANDOMIZATION! it's not natural but it uses natural color gradients and it looks organic and controlleably irridescent / pastel parameters.
For perlin, you can use this function, it is a fast zig zag version of perlin.
function zig ( xx : float ): float{ //lfo nz -1,1
xx= xx+32;
var x0 = Mathf.Floor(xx);
var x1 = x0+1;
var v0 = (Mathf.Sin (x0*.014686)*31718.927)%1;
var v1 = (Mathf.Sin (x1*.014686)*31718.927)%1;
return Mathf.Lerp( v0 , v1 , (xx)%1 )*2-1;
}
i am currently working on this and planning on releasing it as a jQuery-ui plugin.
-> http://coulisse.luvdasun.com/
please let me know if you are interested and what you are hoping to see in such a plugin.
gr
As others have commented, classnames utility is the currently recommended approach to handle conditional CSS class names in ReactJs.
In your case, the solution will look like:
var btnGroupClasses = classNames(
'btn-group',
'pull-right',
{
'show': this.props.showBulkActions,
'hidden': !this.props.showBulkActions
}
);
...
<div className={btnGroupClasses}>...</div>
As a side note, I would suggest you to try to avoid using both show
and hidden
classes, so the code could be simpler. Most likely you don't need to set a class for something to be shown by default.
As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.
It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.
library(grid)
library(gridExtra)
library(plyr)
# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))
# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") +
xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category))
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") +
labs(title = "Proportion of total Frequency accounted by each Category in given Year")
# bring them together
grid.arrange(totals,proportion)
This will give you a 2 panel display like this:
If you want to add Frequency values a table is the best format.
The definition for DTO can be found on Martin Fowler's site. DTOs are used to transfer parameters to methods and as return types. A lot of people use those in the UI, but others inflate domain objects from them.
157/32 is int/int
, which results in an int
.
Try using the double literal - 157/32d
, which is int/double
, which results in a double
.
A lookahead regex syntax can help you to achieve your goal. Thus a regex for your example is
.*?quick.*?(?=z)
And it's important to notice the .*?
lazy matching before the (?=z)
lookahead: the expression matches a substring until a first occurrence of the z
letter.
Here is C# code sample:
const string text = "The quick red fox jumped over the lazy brown dogz";
string lazy = new Regex(".*?quick.*?(?=z)").Match(text).Value;
Console.WriteLine(lazy); // The quick red fox jumped over the la
string greedy = new Regex(".*?quick.*(?=z)").Match(text).Value;
Console.WriteLine(greedy); // The quick red fox jumped over the lazy brown dog
You can use the re
module for regexes, but regexes are probably overkill for what you want. I might try something like
z.write(article[:article.index("</html>") + 7]
This is much cleaner, and should be much faster than a regex based solution.
Its important to remember Python 3 has a different way to represent strings - they are byte arrays.
Using Django 1.9 and Python 2.7 and sending the JSON data in the main body (not a header) you would use something like:
mydata = json.loads(request.body)
But for Django 1.9 and Python 3.4 you would use:
mydata = json.loads(request.body.decode("utf-8"))
I just went through this learning curve making my first Py3 Django app!
In the Eclipse top menu bar:
Windows -> Preferences -> Java -> Compiler -> Errors/Warnings ->
Deprecated and restricted API -> Forbidden reference (access rules): -> change to warning
All the other answers are just focus on the IDE level, these are not the most effective and elegant way to generate getters and setters. If you have tens of attributes, the relevant getters and setters methods will make your class code very verbose.
The best way I ever used to generate getters and setters automatically is using project lombok annotations in your java project, lombok.jar will generate getter and setter method when you compile java code.
You just focus on class attributes/variables naming and definition, lombok will do the rest. This is easy to maintain your code.
For example, if you want to add getter and setter method for age
variable, you just add two lombok annotations:
@Getter @Setter
public int age = 10;
This is equal to code like that:
private int age = 10;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
You can find more details about lombok here: Project Lombok
For the first one: your program will go through the loop once for every row in the result set returned by the query. You can know in advance how many results there are by using mysql_num_rows()
.
For the second one: this time you are only using one row of the result set and you are doing something for each of the columns. That's what the foreach
language construct does: it goes through the body of the loop for each entry in the array $row
. The number of times the program will go through the loop is knowable in advance: it will go through once for every column in the result set (which presumably you know, but if you need to determine it you can use count($row)
).
In my case, the problem was a folder in the project directory containing 300k+ files totaling 11Gb. This was just a temporary folder with images results of some computation. After moving this folder out of the project structure, the slowness disappeared. I hope this can help someone, please check your project structure to see if there is anything that is not necessary.
Here is a very good way to handle this (found on ozgrid):
Let's say your list is on Sheet2
and you wish to use the Validation List with AutoComplete on Sheet1
.
On Sheet1
A1
Enter =Sheet2!A1
and copy down including as many spare rows as needed (say 300 rows total). Hide these rows and use this formula in the Refers to: for a dynamic named range called MyList:
=OFFSET(Sheet1!$A$1,0,0,MATCH("*",Sheet1!$A$1:$A$300,-1),1)
Now in the cell immediately below the last hidden row use Data Validation and for the List Source use =MyList
[EDIT] Adapted version for Excel 2007+ (couldn't test on 2010 though but AFAIK, there is nothing really specific to a version).
Let's say your data source is on Sheet2!A1:A300
and let's assume your validation list (aka autocomplete) is on cell Sheet1!A1
.
Create a dynamic named range MyList
that will depend on the value of the cell where you put the validation
=OFFSET(Sheet2!$A$1,MATCH(Sheet1!$A$1&"*",Sheet2!$A$1:$A$300,0)-1,0,COUNTA(Sheet2!$A:$A))
Add the validation list on cell Sheet1!A1
that will refert to the list =MyList
Caveats
This is not a real autocomplete as you have to type first and then click on the validation arrow : the list will then begin at the first matching element of your list
The list will go till the end of your data. If you want to be more precise (keep in the list only the matching elements), you can change the COUNTA
with a SUMLPRODUCT
that will calculate the number of matching elements
Your source list must be sorted
What about iterating on the /proc virtual file system ? http://linux.die.net/man/5/proc ?
While everybody say that there are no directories and files in s3, but only objects (and buckets), which is absolutely true, I would suggest to take advantage of CommonPrefixes, described in this answer. So, you can do following to get list of "folders" (commonPrefixes) and "files" (objectSummaries):
ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucket.getName()).withPrefix(prefix).withDelimiter(DELIMITER);
ListObjectsV2Result listing = s3Client.listObjectsV2(req);
for (String commonPrefix : listing.getCommonPrefixes()) {
System.out.println(commonPrefix);
}
for (S3ObjectSummary summary: listing.getObjectSummaries()) {
System.out.println(summary.getKey());
}
In your case, for objectSummaries (files) it should return (in case of correct prefix):
users/user-id/contacts/contact-id/file1.txt
users/user-id/contacts/contact-id/file2.txt
for commonPrefixes:
users/user-id/contacts/contact-id/
Reference: https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
As other have mentioned, you will probably end up using a vector of pointers instead.
However, you may want to consider using a ptr_vector instead!
Much simpler actually:
Method 1:
Invoke-Expression $scriptPath $argumentList
Method 2:
& $scriptPath $argumentList
Method 3:
$scriptPath $argumentList
If you have spaces in your scriptPath
, don't forget to escape them `"$scriptPath`"
size_t is defined by the C standard to be the unsigned integer return type of the sizeof operator (C99 6.3.5.4.4), and the argument of malloc and friends (C99 7.20.3.3 etc). The actual range is set such that the maximum (SIZE_MAX) is at least 65535 (C99 7.18.3.2).
However, this doesn't let us determine sizeof(size_t). The implementation is free to use any representation it likes for size_t - so there is no upper bound on size - and the implementation is also free to define a byte as 16-bits, in which case size_t can be equivalent to unsigned char.
Putting that aside, however, in general you'll have 32-bit size_t on 32-bit programs, and 64-bit on 64-bit programs, regardless of the data model. Generally the data model only affects static data; for example, in GCC:
`-mcmodel=small'
Generate code for the small code model: the program and its
symbols must be linked in the lower 2 GB of the address space.
Pointers are 64 bits. Programs can be statically or dynamically
linked. This is the default code model.
`-mcmodel=kernel'
Generate code for the kernel code model. The kernel runs in the
negative 2 GB of the address space. This model has to be used for
Linux kernel code.
`-mcmodel=medium'
Generate code for the medium model: The program is linked in the
lower 2 GB of the address space but symbols can be located
anywhere in the address space. Programs can be statically or
dynamically linked, but building of shared libraries are not
supported with the medium model.
`-mcmodel=large'
Generate code for the large model: This model makes no assumptions
about addresses and sizes of sections.
You'll note that pointers are 64-bit in all cases; and there's little point to having 64-bit pointers but not 64-bit sizes, after all.
window.onload = function() {
var userImage = document.getElementById('imageOtherUser');
var hangoutButton = document.getElementById("hangoutButtonId");
userImage.onclick = function() {
hangoutButton.click(); // this will trigger the click event
};
};
this will do the trick
lambda
is an anonymous function, it is equivalent to:
def func(p):
return p.totalScore
Now max
becomes:
max(players, key=func)
But as def
statements are compound statements they can't be used where an expression is required, that's why sometimes lambda
's are used.
Note that lambda
is equivalent to what you'd put in a return statement of a def
. Thus, you can't use statements inside a lambda
, only expressions are allowed.
What does max
do?
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.
So, it simply returns the object that is the largest.
How does key
work?
By default in Python 2 key
compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).
To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key
argument.
Example 1:
A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.
>>> lis = ['1', '100', '111', '2']
Here max
compares the items using their original values (strings are compared lexicographically so you'd get '2'
as output) :
>>> max(lis)
'2'
To compare the items by their integer value use key
with a simple lambda
:
>>> max(lis, key=lambda x:int(x)) # compare `int` version of each item
'111'
Example 2: Applying max
to a list of tuples.
>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]
By default max
will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:
>>> max(lis)
(4, 'e')
But, what if you wanted to compare each item by the value at index 1? Simple: use lambda
:
>>> max(lis, key = lambda x: x[1])
(-1, 'z')
Comparing items in an iterable that contains objects of different type:
List with mixed items:
lis = ['1','100','111','2', 2, 2.57]
In Python 2 it is possible to compare items of two different types:
>>> max(lis) # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x)) # compare integer version of each item
'111'
But in Python 3 you can't do that any more:
>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
max(lis)
TypeError: unorderable types: int() > str()
But this works, as we are comparing integer version of each object:
>>> max(lis, key=lambda x: int(x)) # or simply `max(lis, key=int)`
'111'
You can use wildcards with the del
command, and /S
to do it recursively.
del /S *.jpg
@BmyGuest asked why a downvoted answer (del /s c:\*.blaawbg
) was any different than my answer.
There's a huge difference between running del /S *.jpg
and del /S C:\*.jpg
. The first command is executed from the current location, whereas the second is executed on the whole drive.
In the scenario where you delete jpg
files using the second command, some applications might stop working, and you'll end up losing all your family pictures. This is utterly annoying, but your computer will still be able to run.
However, if you are working on some project, and want to delete all your dll
files in myProject\dll
, and run the following batch file:
@echo off
REM This short script will only remove dlls from my project... or will it?
cd \myProject\dll
del /S /Q C:\*.dll
Then you end up removing all dll
files form your C:\
drive. All of your applications stop working, your computer becomes useless, and at the next reboot you are teleported in the fourth dimension where you will be stuck for eternity.
The lesson here is not to run such command directly at the root of a drive (or in any other location that might be dangerous, such as %windir%
) if you can avoid it. Always run them as locally as possible.
The wildcard method will try to match all file names, in their 8.3 format, and their "long name" format. For example, *.dll
will match project.dll
and project.dllold
, which can be surprising. See this answer on SU for more detailed information.
#created a sorting function to sort by length of elements of list
def sort_len(a):
num = len(a)
d = {}
i = 0
while i<num:
d[i] = len(a[i])
i += 1
b = list(d.values())
b.sort()
c = []
for i in b:
for j in range(num):
if j in list(d.keys()):
if d[j] == i:
c.append(a[j])
d.pop(j)
return c
Your question is: are these not modules capable of declaring variables at global scope?
Answer: YES, they are "capable"
The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1
, e.g.)
References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).
For instance, place in Sheet1 code
Public glob_sh1 As String
Sub test_sh1()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
place in ThisWorkbook code
Public glob_this As String
Sub test_this()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
and in a Standard Module code
Public glob_mod As String
Sub test_mod()
glob_mod = "glob_mod"
ThisWorkbook.glob_this = "glob_this"
Sheet1.glob_sh1 = "glob_sh1"
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
All three subs work fine.
PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).
PS2: Your line Debug.Print ("Hello")
will give you the compile error Invalid outside procedure
.
PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.
PS4: Check also Put Excel-VBA code in module or sheet?.
PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.
PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.
For .nupkg files I like to use:
Install-Package C:\Path\To\Some\File.nupkg
I had just the same trouble with fedora 26 and LVM partitions, it seems I forgot check something during the installation, So, my 15G root directory has been increased to 227G like I needed.
I posted the steps I followed here:
resize2fs: Bad magic number in super-block while trying to open
0) #df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 1.9G 0 1.9G 0% /dev
tmpfs 1.9G 0 1.9G 0% /dev/shm
tmpfs 1.9G 824K 1.9G 1% /run
tmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup
/dev/mapper/fedora-root 15G 2.1G 13G 14% /
tmpfs 1.9G 0 1.9G 0% /tmp
/dev/md126p1 976M 119M 790M 14% /boot
tmpfs 388M 0 388M 0% /run/user/0
1) # vgs
VG #PV #LV #SN Attr VSize VFree
fedora 1 2 0 wz--n- 231.88g 212.96g
2) # vgdisplay
--- Volume group ---
VG Name fedora
System ID
Format lvm2
Metadata Areas 1
Metadata Sequence No 3
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 2
Open LV 2
Max PV 0
Cur PV 1
Act PV 1
VG Size 231.88 GiB
PE Size 4.00 MiB
Total PE 59361
Alloc PE / Size 4844 / 18.92 GiB
Free PE / Size 54517 / 212.96 GiB
VG UUID 9htamV-DveQ-Jiht-Yfth-OZp7-XUDC-tWh5Lv
3) # lvextend -l +100%FREE /dev/mapper/fedora-root
Size of logical volume fedora/root changed from 15.00 GiB (3840 extents) to 227.96 GiB (58357 extents).
Logical volume fedora/root successfully resized.
4) #lvdisplay
5) #fd -h
6) # xfs_growfs /dev/mapper/fedora-root
meta-data=/dev/mapper/fedora-root isize=512 agcount=4, agsize=983040 blks
= sectsz=512 attr=2, projid32bit=1
= crc=1 finobt=1 spinodes=0 rmapbt=0
= reflink=0
data = bsize=4096 blocks=3932160, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=1
log =internal bsize=4096 blocks=2560, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
data blocks changed from 3932160 to 59757568
7) #df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 1.9G 0 1.9G 0% /dev
tmpfs 1.9G 0 1.9G 0% /dev/shm
tmpfs 1.9G 828K 1.9G 1% /run
tmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup
/dev/mapper/fedora-root 228G 2.3G 226G 2% /
tmpfs 1.9G 0 1.9G 0% /tmp
/dev/md126p1 976M 119M 790M 14% /boot
tmpfs 388M 0 388M 0% /run/user/0
Best regards,
You can try this:
input[type='text'] {
background-image: url(images/comment-author.gif);
background-position: 7px 7px;
background-repeat: no-repeat;
}
My solution is similar to molokoloco. Written as jQuery function:
$.fn.waitForImages = function (callback) {
var $img = $('img', this),
totalImg = $img.length;
var waitImgLoad = function () {
totalImg--;
if (!totalImg) {
callback();
}
};
$img.each(function () {
if (this.complete) {
waitImgLoad();
}
})
$img.load(waitImgLoad)
.error(waitImgLoad);
};
example:
<div>
<img src="img1.png"/>
<img src="img2.png"/>
</div>
<script>
$('div').waitForImages(function () {
console.log('img loaded');
});
</script>
I found elegant work around for me to remove symbols and continue to keep string as string in follows:
yourstring = yourstring.encode('ascii', 'ignore').decode('ascii')
It's important to notice that using the ignore option is dangerous because it silently drops any unicode(and internationalization) support from the code that uses it, as seen here (convert unicode):
>>> u'City: Malmö'.encode('ascii', 'ignore').decode('ascii')
'City: Malm'
Really late reply for me, but I just suffered the pain of this problem as well.
What fixed it for me (after trying the Axis label settings and intervals from those screens, none of which worked!) was select the Horizontal Axis, then when you can see all the properties find Labels, and change LabelInterval to 1.
For some reason when I set this from the pop up properties screens it either never 'stuck' or it changes a slightly different value that didn't fix my issue.
Just tell request that you are using json:true and forget about header and parse
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'GET',
json:true
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
and the same for post
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'POST',
json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
did you check boostrap website? search for "forms"
<div class="form-row">
<div class="col">
<input type="text" class="form-control" placeholder="First name">
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Last name">
</div>
SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.
There are a few third-party extensions that provide that capability - check out e.g.:
I was reading something related to this try if it is useful.
1.Define a push function inside a object.
let obj={push:function push(element){ [].push.call(this,element)}};
Now you can push elements like an array
obj.push(1)
obj.push({a:1})
obj.push([1,2,3])
This will produce this object
obj={
0: 1
1: {a: 1}
2: (3) [1, 2, 3]
length: 3
}
Notice the elements are added with indexes and also see that there is a new length property added to the object.This will be useful to find the length of the object too.This works because of the generic nature of push()
function
I have only been working with it for a few weeks but I don't believe that this is strictly possible however you should be able to get the same effect with a little more effort; just write the query yourself and annotate the method name. It's probably not much simpler than writing the method yourself but it is cleaner in my opinion.
Edit: it is now possible according to DATAJPA-231
I tried the following code that seemed to work:
if(open(my $FILE, "<File.txt")) {
while(<$FILE>){
print "$_";}
} else {
print "File could not be opened or did not exists\n";
}
For the second part of your question, "get usage statistics of the given partition", psutil makes this easy with the disk_usage(path) function. Given a path, disk_usage()
returns a named tuple including total, used, and free space expressed in bytes, plus the percentage usage.
Simple example from documentation:
>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
Psutil works with Python versions from 2.6 to 3.6 and on Linux, Windows, and OSX among other platforms.
@RequestMapping(value="/") public String home(HttpServletRequest request){
System.out.println("My Attribute :: "+request.getAttribute("YourAttributeName"));
return "home";
}
this is more likely happening because somewhere along your certificate chain you have a certificate, more likely an old root, which is still signed with the MD2RSA algorythm.
You need to locate it into your certificate store and delete it.
Then get back to your certification authority and ask them for then new root.
It will more likely be the same root with the same validity period but it has been recertified with SHA1RSA.
Hope this help.
When you declare a variable, you need to declare its type - in this case: int
. Also you've put a random comma in the while
loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:
int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
sum += numbers[i];
}
System.out.println("The sum is: " + sum);
As Internet Explorer doesn't natively support rounded corners. So a better cross-browser way to handle it would be to use rounded-corner images at the corners. Many famous websites use this approach.
You can also find rounded image generators around the web. One such link is http://www.generateit.net/rounded-corner/
ncurses provides a nice way to do this! Also this is my very first post (that I can remember), so any comments at all are welcome. I will appreciate useful ones, but all are welcome!
to compile: g++ -std=c++11 -pthread -lncurses .cpp -o
#include <iostream>
#include <ncurses.h>
#include <future>
char get_keyboard_input();
int main(int argc, char *argv[])
{
initscr();
raw();
noecho();
keypad(stdscr,true);
auto f = std::async(std::launch::async, get_keyboard_input);
while (f.wait_for(std::chrono::milliseconds(20)) != std::future_status::ready)
{
// do some work
}
endwin();
std::cout << "returned: " << f.get() << std::endl;
return 0;
}
char get_keyboard_input()
{
char input = '0';
while(input != 'q')
{
input = getch();
}
return input;
}
Another option is the janitor
package:
df <- remove_empty_cols(df)
In your example there is no big difference between str -> str
and Function.identity()
since internally it is simply t->t
.
But sometimes we can't use Function.identity
because we can't use a Function
. Take a look here:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
this will compile fine
int[] arrayOK = list.stream().mapToInt(i -> i).toArray();
but if you try to compile
int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();
you will get compilation error since mapToInt
expects ToIntFunction
, which is not related to Function
. Also ToIntFunction
doesn't have identity()
method.
Solution is here:
SomeModel.last(5).reverse
Since rails is lazy, it will eventually hit the database with SQL like: "SELECT table
.* FROM table
ORDER BY table
.id
DESC LIMIT 5".
With this command I had poor image quality
ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -vcodec copy -acodec copy -f mp4 -y MyVideoFFmpeg.mp4
With this, almost without delay, I got good image quality.
ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -b 900k -vcodec copy -r 60 -y MyVdeoFFmpeg.avi
If Options -Indexes
does not work as Bryan Drewery suggested, you could write a recursive method to create blank index.php files.
Place this inside of your base folder you wish to protect, you can name it whatever (I would recommend index.php)
<?php
recurse(".");
function recurse($path){
foreach(scandir($path) as $o){
if($o != "." && $o != ".."){
$full = $path . "/" . $o;
if(is_dir($full)){
if(!file_exists($full . "/index.php")){
file_put_contents($full . "/index.php", "");
}
recurse($full);
}
}
}
}
?>
These blank index.php files can be easily deleted or overwritten, and they'll keep your directories from being listable.
I like the solution from @Pho3niX83...
Let's extend it with "word" instead of "char"...
function trimWord(_string, _word) {
var splitted = _string.split(_word);
while (splitted.length && splitted[0] === "") {
splitted.shift();
}
while (splitted.length && splitted[splitted.length - 1] === "") {
splitted.pop();
}
return splitted.join(_word);
};
yes,Just reinstall numpy,it works.
If you have lots of commits and you only want to squash the last X commits, find the commit ID of the commit from which you want to start squashing and do
git rebase -i <that_commit_id>
Then proceed as described in leopd's answer, changing all the pick
s to squash
es except the first one.
871adf OK, feature Z is fully implemented --- newer commit --+
0c3317 Whoops, not yet... |
87871a I'm ready! |
643d0e Code cleanup |-- Join these into one
afb581 Fix this and that |
4e9baa Cool implementation |
d94e78 Prepare the workbench for feature Z -------------------+
6394dc Feature Y --- older commit
You can either do this (write the number of commits):
git rebase --interactive HEAD~[7]
Or this (write the hash of the last commit you don't want to squash):
git rebase --interactive 6394dc
Mine is better! :)
extension UIApplication {
var visibleViewController : UIViewController? {
return keyWindow?.rootViewController?.topViewController
}
}
extension UIViewController {
fileprivate var topViewController: UIViewController {
switch self {
case is UINavigationController:
return (self as! UINavigationController).visibleViewController?.topViewController ?? self
case is UITabBarController:
return (self as! UITabBarController).selectedViewController?.topViewController ?? self
default:
return presentedViewController?.topViewController ?? self
}
}
}
This worked for me, in my case I had a button with a data-id attribute:
$("a").data("item-id");
This approach always works for me:
# First of all, delete all broken links. Replace my_project_name` to your virtual env name
find ~/.virtualenvs/my_project_name/ -type l -delete
# Then create new links to the current Python version
virtualenv ~/.virtualenvs/my_project_name/
# It's it. Just repeat for each virtualenv located in ~/.virtualenvs
Taken from:
The screen widths Bootstrap v3.x uses are as follows:
Extra small devices
Phones (<768px)
/ .col-xs-
Small devices
Tablets (=768px)
/ .col-sm-
Medium devices
Desktops (=992px)
/ .col-md-
Large devices
Desktops (=1200px)
/ .col-lg-
So, these are good to use and work well in practice.
I was able to achieve this in ASP.NET MVC using the client IP address and freegeoip.net API. freegeoip.net is free and does not require any license.
Below is the sample code I used.
String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
string url = "http://freegeoip.net/json/" + UserIP.ToString();
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;
You can go through this post for more details.Hope it helps!
In my case, only thing that helped me is to re-install (or repair is easier) IIS 10.0 Express
This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested above you might also use strptime()
which is (IMHO) easier to read and perhaps the preferred way to do this conversion.
import datetime
s = "20120213"
s_datetime = datetime.datetime.strptime(s, '%Y%m%d')
In v4 change the SASS variable:
$font-size-base: 1rem !default;
If you dont want to modify the xtick labels, you can just use:
plt.xticks(rotation=45)