In my case my site on IIS was pointing to a different project than the one I was running on visual studio.
I just ran into this error and it took days to resolve. We were thrown for a loop by the red-herring error message mentioned in the initial question, plus the Windows Event Viewer error log indicated something similar:
Login failed for user '(domain\name-PC)$'. Reason: Could not find a login matching the name provided. [CLIENT: <local machine>]
Neither of these was true, the user had all the necessary permissions in SQL Server.
In our case, the solution was to switch the Application Pool Identity in IIS to NetworkService
.
I resolved this problem by following steps:
may be it help you to.
For me it was only crashing with this error on a production environment, not on local machine; what solved it was to delete the content of /bin folder and then to regenerate it again.
We recently upgraded to the NuGet version of SqlClient
(Microsoft.Data.SqlClient
) which contains a bug. This bug was introduced during the lifetime of the 1.x cycle and has already been fixed. The fix will be available in the 2.0.0 release which is not available at the time of this writing. A preview is available.
You can inspect the details here: https://github.com/dotnet/SqlClient/issues/262
I hit this in MVC 5 and Visual Studio Express 2013. I had two properties with an IndexAttribute
like below. Commenting out one of them and recompiling resulted in scaffolding the MVC 5 controller with views, using Entity Framework succeeding. Mysteriously, when I uncommented the attribute, recompiled, and tried again, the scaffolder ran just fine.
Perhaps the underlying entity data model or "something" was cached/corrupted, and removing and re-adding the IndexAttribute
simply triggered a rebuild of that "something".
[Index(IsUnique = true)]
public string Thing1 { get; set; }
[Index(IsUnique = true)]
public string Thing2 { get; set; }
I get this one all the time. It means that the user started to download a file, and then it either failed, or they cancelled it.
To reproduce the exception try do this yourself - however I'm unaware of any ways to prevent it (except for handling this specific exception only).
You need to decide what the best way forward is depending on your app.
We were getting the same error - so this may be useful to some.
For us the cause was super simple. An interface change confused an end user and they were pressing the back button in the browser at a 'bad' time after a form submission (sure we should probably have used a PRG pattern, but we didn't).
We fixed the issue and the user is no longer pressing the back button. Problem solved.
TLDR: Check that you don't connect to the same table/view twice.
FooConfiguration.cs
builder.ToTable("Profiles", "dbo");
...
BarConfiguration.cs
builder.ToTable("profiles", "dbo");
For me the issue was that I was trying to add an entity that connected to the same table as some other entity that already existed.
I added a new DbSet with entity and config, thinking we don't have it in our solution yet, however after searching for table name through all solution I found another place where we already connected to it.
Switching to use existing DbSet and removing my newly added one solved the issue.
This error occurs due to mismatch of Service name in .SVC file. Probably you might have changed the name of the service class that is implementing the interface.The Solution is to open .SVC file and exactly match the Service attribute and CodeBehind Attribute. So your .SVC file should be like
<%@ ServiceHost Language="Language you are using" Debug="bool value to enable debugging" Service="Service class name that is implementing your Service interface" Codebehind="~/Appcode/Class implementing interface.cs"%>. for eg.
<%@ ServiceHost Language="C#" Debug="true" Service="Product.Service" CodeBehind="~/AppCode/Product.Service.cs"%>
This example is for .svc file that is using C# language, with debugging enabled, Service class implementing interface and this class is within app folder with name Service.cs and Product is namespace for Service class.
Also Please make respective change in service config file.
<system.serviceModel>
<services>
<service name="Product.Service" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="Product.Iservice">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<behavior name="ServiceBehavior">
<serviceMetaData httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</behaviors>
</system.serviceModel>
Use the Path
class from System.IO
. It contains useful calls for manipulating file paths, including GetDirectoryName
which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);
Increasing number of max-connections will not solve the problem.
We were experiencing the same situation on our servers. This is what happens
User open a page/view, that connect to the database, query the database, still query(queries) were not finished and user leave the page or move to some other page. So the connection that was open, will remains open, and keep increasing number of connections, if there are more users connecting with the db and doing something similar.
You can set interactive_timeout MySQL, bydefault it is 28800 (8hours) to 1 hour
SET interactive_timeout=3600
CREATE PROCEDURE [dbo].[USP_StudentInformation]
@S_Name VARCHAR(50)
,@S_Address VARCHAR(500)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Date VARCHAR(50)
SET @Date = GETDATE()
IF EXISTS (
SELECT *
FROM TB_StdFunction
WHERE S_Name = @S_Name
AND S_Address = @S_Address
)
BEGIN
UPDATE TB_StdFunction
SET S_Name = @S_Name
,S_Address = @S_Address
,ModifiedDate = @Date
WHERE S_Name = @S_Name
AND S_Address = @S_Address
SELECT *
FROM TB_StdFunction
END
ELSE
BEGIN
INSERT INTO TB_StdFunction (
S_Name
,S_Address
,CreatedDate
)
VALUES (
@S_Name
,@S_Address
,@date
)
SELECT *
FROM TB_StdFunction
END
END
Table Name : TB_StdFunction
S_No INT PRIMARY KEY AUTO_INCREMENT
S_Name nvarchar(50)
S_Address nvarchar(500)
CreatedDate nvarchar(50)
ModifiedDate nvarchar(50)
few day ago I have the SAME problem with 1 table.
Firstly try:
echo json_encode($rows);
echo json_last_error(); // returns 5 ?
If last line returns 5, problem is with your data. I know, your tables are in UTF-8, but not entered data. For example the input was in txt file, but created on Win machine with stupid encoding (in my case Win-1250 = CP1250) and this data has been entered into the DB.
Solution? Look for new data (excel, web page), edit source txt file via PSPad (or whatever else), change encoding to UTF-8, delete all rows and now put data from original. Save. Enter into DB.
You can also only change encoding to utf-8 and then change all rows manually (give cols with special chars - desc, ...). Good for slaves...
must declare a body because it is not marked abstract, extern, or partialI had the same problem here:
private static void swapMth(ref int x, ref int y);
{
int num = x;
x = y;
y = num;
}
private void button_Click(object sender, EventArgs e)
{
int x = 10;
int y = 20;
labelResult.Text = $"Befor n1 = {x} , n2={y} ";
swapMth(ref x, ref y);
labelResult.Text += $"\n After n1 = {x} , n2={y}";
}
And it was solved by deleting ";" from the method line:
private static void swapMth(ref int x, ref int y); PROBLEM
to
private static void swapMth(ref int x, ref int y) SOLVED
I know it is basic mistake, hope someone could get help by this note.
private static void swapMth(ref int x, ref int y)
{
int num = x;
x = y;
y = num;
}
private void button_Click(object sender, EventArgs e)
{
int x = 10;
int y = 20;
labelResult.Text = $"Befor n1 = {x} , n2={y} ";
swapMth(ref x, ref y);
labelResult.Text += $"\n After n1 = {x} , n2={y}";
}
You can make this happen with less typing. First, change the way your push works:
git config --global push.default current
This will infer the origin my_branch
part, thus you can do:
git push -u
Which will both create the remote branch with the same name and track it.
if you want to modify or update NSDictionary then first of all typecast it as NSMutableDictionary
let newdictionary = NSDictionary as NSMutableDictionary
then simply use
newdictionary.setValue(value: AnyObject?, forKey: String)
I prefer using the dateutil library for timezone handling and generally solid date parsing. If you were to get an ISO 8601
string like: 2010-05-08T23:41:54.000Z
you'd have a fun time parsing that with strptime, especially if you didn't know up front whether or not the timezone was included. pyiso8601
has a couple of issues (check their tracker) that I ran into during my usage and it hasn't been updated in a few years. dateutil, by contrast, has been active and worked for me:
import dateutil.parser
yourdate = dateutil.parser.parse(datestring)
Android Home should be the root folder of SDK.
export ANDROID_HOME="$HOME/android-sdk-linux"
EDIT: Open terminal and type these commands. (yes, on a ternimal , not in bashrc file)
export ANDROID_HOME=~/android-sdk-macosx
PATH=$PATH:$ANDROID_HOME/tools
PATH=$PATH:$ANDROID_HOME/platform-tools
and then in the same terminal just type android
. If configured you would be able to use build commands from this terminal. (it's a temporary solution)
This question reminds of how to determine equality for two JavaScript objects. So, I would choose this general function
Compares JS objects:
function objectEquals(x, y) {
// if both are function
if (x instanceof Function) {
if (y instanceof Function) {
return x.toString() === y.toString();
}
return false;
}
if (x === null || x === undefined || y === null || y === undefined) { return x === y; }
if (x === y || x.valueOf() === y.valueOf()) { return true; }
// if one of them is date, they must had equal valueOf
if (x instanceof Date) { return false; }
if (y instanceof Date) { return false; }
// if they are not function or strictly equal, they both need to be Objects
if (!(x instanceof Object)) { return false; }
if (!(y instanceof Object)) { return false; }
var p = Object.keys(x);
return Object.keys(y).every(function (i) { return p.indexOf(i) !== -1; }) ?
p.every(function (i) { return objectEquals(x[i], y[i]); }) : false;
}
If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.
$scope.login = function () {
$scope.btntext = "Please wait...!";
$http({
method: "POST",
url: '/Home/userlogin', // link UserLogin with HomeController
data: $scope.user
}).then(function (response) {
console.log("Result value is : " + parseInt(response));
data = response.data;
$scope.btntext = 'Login';
if (data == 1) {
window.location.href = '/Home/dashboard';
}
else {
alert(data);
}
}, function (error) {
alert("Failed Login");
});
The above snipit works for a login page.
I've had a very similar issue using spring-boot-starter-data-redis
. To my implementation there was offered a @Bean
for RedisTemplate
as follows:
@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));
// Add some specific configuration here. Key serializers, etc.
return template;
}
The fix was to specify an array of RoutePlantCache
as following:
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));
Below the exception I had:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]
You can also specify the font size relative to the base_size
included in themes such as theme_bw()
(where base_size
is 11) using the rel()
function.
For example:
ggplot(mtcars, aes(disp, mpg, col=as.factor(cyl))) +
geom_point() +
theme_bw() +
theme(legend.text=element_text(size=rel(0.5)))
According to JavaDocs, you can do this:
WebElement input = divA.findElement(By.xpath(".//input"));
How can I ask in xpath for "the div-tag that contains a span with the text 'hello world'"?
WebElement elem = driver.findElement(By.xpath("//div[span[text()='hello world']]"));
The XPath spec is a suprisingly good read on this.
Unless you are writing very small files, you should probably use templates.
Example:
- name: copy upstart script
template:
src: myCompany-service.conf.j2
dest: "/etc/init/myCompany-service.conf"
Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.
If you make Dict
into an object, this will work:
var dict = {};
var addPair = function (myKey, myValue) {
dict[myKey] = myValue;
};
var giveValue = function (myKey) {
return dict[myKey];
};
The myKey
variable is already a string, so you don't need more quotes.
Using ADO (AnonJr already explained) and utilizing SQL is possibly the best option for fetching data from a closed workbook without opening that in conventional way. Please watch this VIDEO.
OTHERWISE, possibly GetObject(<filename with path>)
is the most CONCISE way. Worksheets remain invisible, however will appear in project explorer window in VBE just like any other workbook opened in conventional ways.
Dim wb As Workbook
Set wb = GetObject("C:\MyData.xlsx") 'Worksheets will remain invisible, no new window appears in the screen
' your codes here
wb.Close SaveChanges:=False
If you want to read a particular sheet, need not even define a Workbook variable
Dim sh As Worksheet
Set sh = GetObject("C:\MyData.xlsx").Worksheets("MySheet")
' your codes here
sh.Parent.Close SaveChanges:=False 'Closes the associated workbook
However, There is one more way to check the object in jQuery.
jQuery.type(a); //this returns type of variable.
I have made example to understand things, jsfiddle link
Enter "about:config" into the Firefox address bar and set:
browser.cache.disk.enable = false
browser.cache.memory.enable = false
If developing locally, or using HTML5's new manifest attribute you may have to also set the following in about:config -
browser.cache.offline.enable = false
npm install -g increase-memory-limit
increase-memory-limit
OR
C:\Users\{user_name}\AppData\Roaming\npm
--max_old_space_size=8192
to the IF
and ELSE
blocknow ng.cmd file looks like this after the change:
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
)
Unless you are doing a DB to track historical times more than a century ago, using
Modified datetime DEFAULT ((0))
is perfectly safe and sound and allows more elegant queries than '1753-01-01' and more efficient queries than NULL
.
However, since first Modified datetime
is the time at which the record was inserted, you can use:
Modified datetime NOT NULL DEFAULT (GETUTCDATE())
which avoids the whole issue and makes your inserts easier and safer - as in you don't insert it at all and SQL does the housework :-)
With that in place you can still have elegant and fast queries by using 0 as a practical minimum since it's guranteed to always be lower than any insert-generated GETUTCDATE()
.
To remove all files from a directory, first you need to list all files in the directory using fs.readdir
, then you can use fs.unlink
to remove each file. Also fs.readdir
will give just the file names, you need to concat with the directory name to get the full path.
Here is an example
const fs = require('fs');
const path = require('path');
const directory = 'test';
fs.readdir(directory, (err, files) => {
if (err) throw err;
for (const file of files) {
fs.unlink(path.join(directory, file), err => {
if (err) throw err;
});
}
});
There is a recursive
flag that you can use in rmdir
to remove all the files recursively. See nodejs docs for more information.
const fs = require('fs').promises;
const directory = 'test';
fs.rmdir(directory, { recursive: true })
.then(() => console.log('directory removed!'));
If you are running your script at linux environment you can use this command:
bsub -q server_name -R "rusage[mem=requested_memory]" "Rscript script_name.R"
and the server will allocate the requested memory for you (according to the server limits, but with good server - hugefiles can be used)
In Python 2.7 and 3 you can use this:
import string
string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
As @Zaz says:
string.lowercase
is deprecated and no longer works in Python 3 but string.ascii_lowercase
works in both
You may find your answer in the javadoc of Map#put(K, V) (which actually returns something):
public V put(K key, V value)
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this key, the old value is replaced by the specified value. (A map
m
is said to contain a mapping for a keyk
if and only ifm.containsKey(k)
would returntrue
.)Parameters:
key
- key with which the specified value is to be associated.
value
- value to be associated with the specified key.Returns:
previous value associated with specified key, ornull
if there was no mapping forkey
. (Anull
return can also indicate that the map previously associatednull
with the specifiedkey
, if the implementation supportsnull
values.)
So if you don't assign the returned value when calling mymap.put("1", "a string")
, it just becomes unreferenced and thus eligible for garbage collection.
For your specific data, you can use
Select col1, col2, LTRIM(RTRIM(SUBSTRING(
STUFF(col3, CHARINDEX('|', col3,
PATINDEX('%|Client Name =%', col3) + 14), 1000, ''),
PATINDEX('%|Client Name =%', col3) + 14, 1000))) col3
from Table01
Test
select col3='Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0151|Info = INF8888877 -MAC333330554/444400800'
into t1m
from master..spt_values a
cross join master..spt_values b
where a.number < 100
-- (711704 row(s) affected)
set statistics time on
dbcc dropcleanbuffers
dbcc freeproccache
select a=CHARINDEX('|Client Name =', col3) into #tmp1 from t1m
drop table #tmp1
dbcc dropcleanbuffers
dbcc freeproccache
select a=PATINDEX('%|Client Name =%', col3) into #tmp2 from t1m
drop table #tmp2
set statistics time off
Timings
CHARINDEX:
SQL Server Execution Times (1):
CPU time = 5656 ms, elapsed time = 6418 ms.
SQL Server Execution Times (2):
CPU time = 5813 ms, elapsed time = 6114 ms.
SQL Server Execution Times (3):
CPU time = 5672 ms, elapsed time = 6108 ms.
PATINDEX:
SQL Server Execution Times (1):
CPU time = 5906 ms, elapsed time = 6296 ms.
SQL Server Execution Times (2):
CPU time = 5860 ms, elapsed time = 6404 ms.
SQL Server Execution Times (3):
CPU time = 6109 ms, elapsed time = 6301 ms.
Conclusion
The timings for CharIndex and PatIndex for 700k calls are within 3.5% of each other, so I don't think it would matter whichever is used. I use them interchangeably when both can work.
Use a dot or a pipe as the field separator:
awk -v FS='[.|]' '{
printf "%s%s %s.%s\n", toupper(substr($4,1,1)), substr($4,2), $1, $2
}' << END
[email protected]|com.emailclient.account
[email protected]|com.socialsite.auth.account
END
gives:
Emailclient [email protected]
Socialsite [email protected]
If your SQL database allows Null values for that field try using int? value
like that :
if (this.txtboxname.Text == "" || this.txtboxname.text == null)
value = null;
else
value = Convert.ToInt32(this.txtboxname.Text);
Take care that Convert.ToInt32 of a null value returns 0 !
Convert.ToInt32(null) returns 0
I just found the VT char in a .pptx document at several places within a table element. But no clue about how it was inserted.
Try:
android:layout_height="wrap_content"
android:scaleType="fitStart"
on the image in the RelativeLayout
Okay this will work 100% for sure.
First you will need to setup listener if keyboard is show or hide. If keyboard is showing then probably user is typing, otherwise done typing.
final View activityRootView = findViewById(android.R.id.content);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
activityRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
isTyping = true;
} else {
//to make sure this will call only once when keyboard is hide.
if(isTyping){
isTyping = false;
}
}
}
});
If it's almost impossible to rule out modifications of the files, have you considered ignoring them? If this statement is right and you wouldn't touch those files during your development, this command may be useful:
git update-index --assume-unchanged file_to_ignore
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
Starting from CSS Selectors 4 using multiple arguments in the :not
selector becomes possible (see here).
In CSS3, the :not selector only allows 1 selector as an argument. In level 4 selectors, it can take a selector list as an argument.
Example:
/* In this example, all p elements will be red, except for
the first child and the ones with the class special. */
p:not(:first-child, .special) {
color: red;
}
Unfortunately, browser support is limited. For now, it only works in Safari.
This issue is because sometimes you need to again update/create the database or sometimes if you have added the field in db table but not not entity class then it can not insert any null value or zero so this error came. So check both side.Db and Entity class.
You can also do it this way
private static string GetPaddingSequence(int padding)
{
StringBuilder SB = new StringBuilder();
for (int i = 0; i < padding; i++)
{
SB.Append("0");
}
return SB.ToString();
}
public static string FormatNumber(int number, int padding)
{
return number.ToString(GetPaddingSequence(padding));
}
Finally call the function FormatNumber
string x = FormatNumber(1,2);
Output will be 01 which is based on your padding parameter. Increasing it will increase the number of 0s
As per Apple's documentation:
(void)beginAppearanceTransition:(BOOL)isAppearing animated:(BOOL)animated;
Description:
Tells a child controller its appearance is about to change.
If you are implementing a custom container controller, use this method to tell the child that its views are about to appear or disappear. Do not invoke viewWillAppear:
, viewWillDisappear:
, viewDidAppear:
, or viewDidDisappear:
directly.
(void)endAppearanceTransition;
Description:
Tells a child controller its appearance has changed. If you are implementing a custom container controller, use this method to tell the child that the view transition is complete.
Sample code:
(void)applicationDidEnterBackground:(UIApplication *)application
{
[self.window.rootViewController beginAppearanceTransition: NO animated: NO]; // I commented this line
[self.window.rootViewController endAppearanceTransition]; // I commented this line
}
Question: How I fixed?
Ans: I found this piece of lines in application. This lines made my app not recieving any ViewWillAppear notification's. When I commented these lines it's working fine.
In more or less normal parlance: If your software can do everything the mimicked system can do, it's an emulator. If it only approximates the results of a system (IT or otherwise), it's a simulator.
GitHub
git config --global url.ssh://[email protected]/.insteadOf https://github.com/
BitBucket
git config --global url.ssh://[email protected]/.insteadOf https://bitbucket.org/
That tells git to always use SSH instead of HTTPS when connecting to GitHub/BitBucket, so you'll authenticate by certificate by default, instead of being prompted for a password.
The format is %lu
.
Please check about the various other datatypes and their usage in printf here
Boolean(val) === false. This worked for me to check if value was falsely.
Easy,Tested and working 100%
Import webkit :
import WebKit
Assign IBOutlet to webview:
var webView : WKWebView!
set delegate:
class ViewController: UIViewController , WKNavigationDelegate{
Write code on viewDidLoad():
// loading URL :
let myBlog = "https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile"
let url = NSURL(string: myBlog)
let request = NSURLRequest(url: url! as URL)
// init and load request in webview.
webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.load(request as URLRequest)
self.view.addSubview(webView)
self.view.sendSubview(toBack: webView)
Write delegate methods:
//MARK:- WKNavigationDelegate
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
print(error.localizedDescription)
}
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Strat to load")
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
print("finish to load")
}
Try
mysqldump databaseExample > file.sql
How to write a compound statement with if?
You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.
if %ERRORLEVEL% == 0 (
echo ErrorLevel is zero
echo A second statement
) else if %ERRORLEVEL% == 1 (
echo ErrorLevel is one
echo A second statement
) else (
echo ErrorLevel is > 1
echo A second statement
)
Im late to the party, but this worked great for me and the code should explain itself;
<script type="text/javascript">
function formAJAX(btn){
var $form = $(btn).closest('[action]');
var str = $form.find('[name]').serialize();
$.post($form.attr('action'), str, function(data){
//do stuff
});
}
<script>
HTML:
<tr action="scriptURL.php">
<td>
Field 1:<input type="text" name="field1"/>
</td>
<td>
Field 2:<input type="text" name="field2" />
</td>
<td><button type="button" onclick="formAJAX(this)">Update</button></td>
</tr>
I think this should be:
$('.home').click(function() {
$(this).css('background', 'url(images/tabs3.png)');
});
and remove this:
<div class="home" onclick="function()">
//-----------^^^^^^^^^^^^^^^^^^^^---------no need for this
You have to make sure you have a correct path to your image.
audio /= np.max(np.abs(audio),axis=0)
image *= (255.0/image.max())
Using /=
and *=
allows you to eliminate an intermediate temporary array, thus saving some memory. Multiplication is less expensive than division, so
image *= 255.0/image.max() # Uses 1 division and image.size multiplications
is marginally faster than
image /= image.max()/255.0 # Uses 1+image.size divisions
Since we are using basic numpy methods here, I think this is about as efficient a solution in numpy as can be.
In-place operations do not change the dtype of the container array. Since the desired normalized values are floats, the audio
and image
arrays need to have floating-point point dtype before the in-place operations are performed.
If they are not already of floating-point dtype, you'll need to convert them using astype
. For example,
image = image.astype('float64')
Very simple answer is to use TrimEnd(). Here is the result,
double value = 1.00;
string output = value.ToString().TrimEnd('0');
Output is 1 If my value is 1.01 then my output will be 1.01
Modern browsers now support the:
width: calc(100% - 100px);
To see the list of supported browser versions checkout: Can I use calc() as CSS unit value?
There is a jQuery fallback: css width: calc(100% -100px); alternative using jquery
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
This is a very different style of programming, but I always try to rewrite things that looked like
bar = None
if foo():
bar = "Baz"
if bar is None:
bar = "Quux"
into just:
if foo():
bar = "Baz"
else:
bar = "Quux"
That is to say, I try hard to avoid a situation where some code paths define variables but others don't. In my code, there is never a path which causes an ambiguity of the set of defined variables (In fact, I usually take it a step further and make sure that the types are the same regardless of code path). It may just be a matter of personal taste, but I find this pattern, though a little less obvious when I'm writing it, much easier to understand when I'm later reading it.
var parentDiv = pDoc.parentElement
edit: this is sometimes parentNode
in some cases.
https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement
I believe your question is to change only width of view dynamically, whereas above methods will change layout properties completely to new one, so I suggest to getLayoutParams() from view first, then set width on layoutParams, and finally set layoutParams to the view, so following below steps to do the same.
View view = findViewById(R.id.nutrition_bar_filled);
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);
remap
is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:
:map
and :noremap
are recursive and non-recursive versions of the various mapping commands. For example, if we run:
:map j gg (moves cursor to first line)
:map Q j (moves cursor to first line)
:noremap W j (moves cursor down one line)
Then:
j
will be mapped to gg
.Q
will also be mapped to gg
, because j
will be expanded for the recursive mapping.W
will be mapped to j
(and not to gg
) because j
will not be expanded for the non-recursive mapping.Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.
For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map
and :noremap
), one that works in normal mode (:nmap
and :nnoremap
), one in visual mode (:vmap
and :vnoremap
) and so on.
For more guidance on this, see:
:help :map
:help :noremap
:help recursive_mapping
:help :map-modes
Thanks to the folks on Freenode's #macdev, here is some information:
In the old days before Xcode was on the app-store, it included commandline tools.
Now you get it from the store, and with this new mechanism it can't install extra things outside of the Xcode.app, so you have to manually do it yourself, by:
xcode-select --install
On Xcode 4.x you can check to see if they are installed from within the Xcode UI:
On Xcode 5.x it is now here:
My problem of finding gcc/gdb is that they have been superseded by clang/lldb: GDB missing in OS X v10.9 (Mavericks)
Also note that Xcode contains compiler and debugger, so one of the things installing commandline tools will do is symlink or modify $PATH. It also downloads certain things like git.
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
These lines worked in my case,
ClassLoader classLoader = getClass().getClassLoader();
File fi = new File(classLoader.getResource("test.txt").getFile());
provided test.txt file inside src
IMHO the coolest way is to go via WebDAV (without Network Folder, as this is often not permitted). This can be accomplished via ActiveX Data Objects as layed out in this excellent article excellent article (code can be used directly in Excel, used the concept recently).
Hope this helps!
http://blog.itwarlocks.com/2009/04/28/accessing-webdav-in-microsoft-word-visual-basic/
the original link is dead, but at least the textual content is still available on archive.org: http://web.archive.org/web/20091008034423/http://blog.itwarlocks.com/2009/04/28/accessing-webdav-in-microsoft-word-visual-basic
I had the same problem and solve it by just making header file public.
If you are working on multiple modules in your project. Then your header file needs to be public to be used in other parts of projects. What you need is to select that header file, and in project Utilities view. Change the file from Project/Private to Public. See image below:
Run like:
$ mvn help:describe -DartifactId=maven-war-plugin -DgroupId=org.apache.maven.plugins
for plug-in that have no version. You get output:
Name: Maven WAR Plugin Description: Builds a Web Application Archive (WAR) file from the project output and its dependencies. Group Id: org.apache.maven.plugins Artifact Id: maven-war-plugin Version: 2.2 Goal Prefix: war
Use version that shown in output.
UPDATE If you want to select among list of versions, use http://search.maven.org/ or http://mvnrepository.com/ Note that your favorite Java IDE must have Maven package search dialog. Just check docs.
SUPER UPDATE I also use:
$ mvn dependency:tree
$ mvn dependency:list
$ mvn dependency:resolve
$ mvn dependency:resolve-plugins # <-- THIS
Recently I discover how to get latest version for plug-in (or library) so no longer needs for googling or visiting Maven Central:
$ mvn versions:display-dependency-updates
$ mvn versions:display-plugin-updates # <-- THIS
int secondDimensionSize = nir[0].length;
Each element of the first dimension is actually another array with the length of the second dimension.
My understanding of the words "If the function modifies that value, the modifications appear also within the scope of the calling function for both passing by value and by reference" is that they are an error.
Modifications made in a called function are not in scope of the calling function when passing by value.
Either you have mistyped the quoted words or they have been extracted out of whatever context made what appears to be wrong, right.
Could you please ensure you have correctly quoted your source and if there are no errors there give more of the text surrounding that statement in the source material.
This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.
var fullEntries = dbContext.tbl_EntryPoint
.Join(
dbContext.tbl_Entry,
entryPoint => entryPoint.EID,
entry => entry.EID,
(entryPoint, entry) => new { entryPoint, entry }
)
.Join(
dbContext.tbl_Title,
combinedEntry => combinedEntry.entry.TID,
title => title.TID,
(combinedEntry, title) => new
{
UID = combinedEntry.entry.OwnerUID,
TID = combinedEntry.entry.TID,
EID = combinedEntry.entryPoint.EID,
Title = title.Title
}
)
.Where(fullEntry => fullEntry.UID == user.UID)
.Take(10);
<form>
<div class="form-group">
<label for="nameLabel">Name</label>
<input id="name" name="name" class="form-control" type="text" />
</div>
<div class="form-group">
<label for="PhoneLabel">Phone</label>
<input id="phone" name="phone" class="form-control" type="text" />
</div>
<div class="form-group">
<label for="yearLabel">Year</label>
<input id="year" name="year" class="form-control" type="text" />
</div>
</form>
Take a look in .git/config and make the changes you need.
Alternatively you could use
git remote rm [name of the url you sets on adding]
and
git remote add [name] [URL]
Or just
git remote set-url [URL]
Before you do anything wrong, double check with
git help remote
Here is the complete example (with main method) which can be added as a utility class in your project. All the format mentioned in SimpleDateFormate API is supported in the below method.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang.time.DateUtils;
public class DateUtility {
public static Date parseDate(String inputDate) {
Date outputDate = null;
String[] possibleDateFormats =
{
"yyyy.MM.dd G 'at' HH:mm:ss z",
"EEE, MMM d, ''yy",
"h:mm a",
"hh 'o''clock' a, zzzz",
"K:mm a, z",
"yyyyy.MMMMM.dd GGG hh:mm aaa",
"EEE, d MMM yyyy HH:mm:ss Z",
"yyMMddHHmmssZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
"YYYY-'W'ww-u",
"EEE, dd MMM yyyy HH:mm:ss z",
"EEE, dd MMM yyyy HH:mm zzzz",
"yyyy-MM-dd'T'HH:mm:ssZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSzzzz",
"yyyy-MM-dd'T'HH:mm:sszzzz",
"yyyy-MM-dd'T'HH:mm:ss z",
"yyyy-MM-dd'T'HH:mm:ssz",
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd'T'HHmmss.SSSz",
"yyyy-MM-dd",
"yyyyMMdd",
"dd/MM/yy",
"dd/MM/yyyy"
};
try {
outputDate = DateUtils.parseDate(inputDate, possibleDateFormats);
System.out.println("inputDate ==> " + inputDate + ", outputDate ==> " + outputDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return outputDate;
}
public static String formatDate(Date date, String requiredDateFormat) {
SimpleDateFormat df = new SimpleDateFormat(requiredDateFormat);
String outputDateFormatted = df.format(date);
return outputDateFormatted;
}
public static void main(String[] args) {
DateUtility.parseDate("20181118");
DateUtility.parseDate("2018-11-18");
DateUtility.parseDate("18/11/18");
DateUtility.parseDate("18/11/2018");
DateUtility.parseDate("2018.11.18 AD at 12:08:56 PDT");
System.out.println("");
DateUtility.parseDate("Wed, Nov 18, '18");
DateUtility.parseDate("12:08 PM");
DateUtility.parseDate("12 o'clock PM, Pacific Daylight Time");
DateUtility.parseDate("0:08 PM, PDT");
DateUtility.parseDate("02018.Nov.18 AD 12:08 PM");
System.out.println("");
DateUtility.parseDate("Wed, 18 Nov 2018 12:08:56 -0700");
DateUtility.parseDate("181118120856-0700");
DateUtility.parseDate("2018-11-18T12:08:56.235-0700");
DateUtility.parseDate("2018-11-18T12:08:56.235-07:00");
DateUtility.parseDate("2018-W27-3");
}
}
Another point to add.
Overloading More than one method with Same name. Same or different return type. Different no of parameters or Different type of parameters. In Same Class or Derived class.
int Add(int num1, int num2) int Add(int num1, int num2, int num3) double Add(int num1, int num2) double Add(double num1, double num2)
Can be possible in same class or derived class. Generally prefers in same class. E.g. Console.WriteLine() has 19 overloaded methods.
Can overload class constructors, methods.
Can consider as Compile Time (static / Early Binding) polymorphism.
=====================================================================================================
Overriding cannot be possible in same class. Can Override class methods, properties, indexers, events.
Has some limitations like The overridden base method must be virtual, abstract, or override. You cannot use the new, static, or virtual modifiers to modify an override method.
Can Consider as Run Time (Dynamic / Late Binding) polymorphism.
Helps in versioning http://msdn.microsoft.com/en-us/library/6fawty39.aspx
=====================================================================================================
Helpful Links
http://msdn.microsoft.com/en-us/library/ms173152.aspx Compile time polymorphism vs. run time polymorphism
This works for me
$('ul.questions li a').click(function(event) {
event.preventDefault();
$('.tab').hide();
window.location.hash = this.hash;
$($(this).attr('href')).fadeIn('slow');
});
Check here http://jsbin.com/edicu for a demo with almost identical code
Instead of using $_POST, use $_REQUEST:
HTML:
<form action="" method="post">
<input type="text" name="firstname">
<input type="submit" name="submit" value="Submit">
</form>
PHP:
if(isset($_REQUEST['submit'])){
$test = $_REQUEST['firstname'];
echo $test;
}
There's also xmlstarlet (which is available for Windows as well).
This happens because LatLngBounds()
does not take two arbitrary points as parameters, but SW and NE points
use the .extend()
method on an empty bounds object
var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);
Demo at http://jsfiddle.net/gaby/22qte/
As of Chrome 72, it's possible to use Intl.ListFormat:
const vehicles = ['Motorcycle', 'Bus', 'Car'];_x000D_
_x000D_
const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });_x000D_
console.log(formatter.format(vehicles));_x000D_
// expected output: "Motorcycle, Bus, and Car"_x000D_
_x000D_
const formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' });_x000D_
console.log(formatter2.format(vehicles));_x000D_
// expected output: "Motorcycle, Bus oder Car"_x000D_
_x000D_
const formatter3 = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });_x000D_
console.log(formatter3.format(vehicles));_x000D_
// expected output: "Motorcycle Bus Car"
_x000D_
Please note that this way is in its very earlier stage, so as of the date of posting this answer, expect incompatibility with older versions of Chrome and other browsers.
If you are connecting from Windows Machine A to Windows Machine B (server with SQL Server installed) and are getting this error, you need to do the following:
On Machine B:
If you want to interpret $replace
, you should not use single quotes since they prevent variable substitution.
Try:
echo $LINE | sed -e "s/12345678/${replace}/g"
Transcript:
pax> export replace=987654321
pax> echo X123456789X | sed "s/123456789/${replace}/"
X987654321X
pax> _
Just be careful to ensure that ${replace}
doesn't have any characters of significance to sed
(like /
for instance) since it will cause confusion unless escaped. But if, as you say, you're replacing one number with another, that shouldn't be a problem.
Also see the speeded-up package ujson:
import ujson
with open('data.json', 'wb') as fp:
ujson.dump(data, fp)
You should call plt.show()
only at the end after creating all the plots.
You are getting that error because when the param1
if statements are evaluated, param is always null due to being scoped variables without delayed expansion.
When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.
Also I recommend using if not defined
command to determine if a variable is set.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.
set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if not defined a goto :aPrompt
echo %a%
IF "%a%"=="2" (
title USB WRITE LOCK
echo What do you want to do?
echo 1.Apply USB Write Protection
echo 2.Remove USB Write Protection
::param1
set "param1=%globalparam2%"
goto :param1Check
:param1Prompt
set /p "param1=Enter Choice: "
:param1Check
if not defined param1 goto :param1Prompt
echo !param1!
if "!param1!"=="1" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
echo USB Write is Locked!
)
if "!param1!"=="2" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
echo USB Write is Unlocked!
)
)
pause
endlocal
if u install by brew (on osx)
first run sudo mkdir /data/db
start mondoDB Daemon by typing mongod
(leave it open) and then
run mongo by typing mongo
in new terminal tab
Use tr:first-child
to take the first tr
:
.category_table tr:first-child td {
vertical-align: top;
}
If you have nested tables, and you don't want to apply styles to the inner rows, add some child selectors so only the top-level td
s in the first top-level tr
get the styles:
.category_table > tbody > tr:first-child > td {
vertical-align: top;
}
I think that substr() throws an exception if str only contains the whitespace.
I would modify it to the following code:
string trim(string& str)
{
size_t first = str.find_first_not_of(' ');
if (first == std::string::npos)
return "";
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
}
According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:
{% if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') ) %}
<li>some text</li>
{% endif %}
Edit: Using line_statement_prefix = '#'
* the code would look like this:
# if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') )
<li>some text</li>
# endif
*Here's an example of how you'd specify the line_statement_prefix
in the Environment
:
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml']),
line_statement_prefix='#'
)
Or using Flask:
from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'
$url = "https://chart.googleapis....";
$json = file_get_contents($url);
Now you can either echo the $json variable, if you just want to display the output, or you can decode it, and do something with it, like so:
$data = json_decode($json);
var_dump($data);
Sendmail wasn't working for me so I used msmtp 1.6.2 w32 and most just followed the instructions at DeveloperSide. Here is a quick rundown of the setup for posterity:
Enabled IMAP access under your Gmail account (the one msmtp is sending emails from)
Enable access for less secure apps. Log into your google account and go here
Edit php.ini
, find and change each setting below to reflect the following:
; These are commented out by prefixing a semicolon
;SMTP = localhost
;smtp_port = 25
; Set these paths to where you put your msmtp files.
; I used backslashes in php.ini and it works fine.
; The example in the devside guide uses forwardslashes.
sendmail_path = "C:\wamp64\msmtp\msmtp.exe -d -C C:\wamp64\msmtp\msmtprc.ini -t --read-envelope-from"
mail.log = "C:\wamp64\msmtp\maillog.txt"
Create and edit the file msmtprc.ini
in the same directory as your msmtp.exe
file as follows, replacing it with your own email and password:
# Default values for all accounts
defaults
tls_certcheck off
# I used forward slashes here and it works.
logfile C:/wamp64/msmtp/msmtplog.txt
account Gmail
host smtp.gmail.com
port 587
auth on
tls on
from [email protected]
user [email protected]
password ReplaceWithYourPassword
account default : gmail
open up console and navigate to bin folder and run
JBOSS_HOME/bin > stanalone.sh
Once it is up and running just copy past your war file in
standalone/deployments folder
Thats probably it for jboss 7.1
Restarting VsCode solved it for me!
This might work for you:
cat <<\! >names.txt
> alison
> barb
> charlie
> david
> !
OIFS=$IFS; IFS=$'\n'; NAMES=($(<names.txt)); IFS=$OIFS
echo "${NAMES[@]}"
alison barb charlie david
echo "${NAMES[0]}"
alison
for NAME in "${NAMES[@]}";do echo $NAME;done
alison
barb
charlie
david
var flag = 0;
$('#target').click(function() {
flag = 1;
});
if (flag == 1)
{
alert("Clicked");
}
else
{
alert("Not clicked");
}
I had some issues with the MouseDown part of this, but here is some code that might get your started.
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Control VerticalAlignment="Top">
<Control.Template>
<ControlTemplate>
<StackPanel>
<TextBox x:Name="MyText"></TextBox>
<Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
<Border Background="Red">
<TextBlock>Test Popup Content</TextBlock>
</Border>
</Popup>
</StackPanel>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
<DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
<DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Control.Template>
</Control>
</Grid>
</Window>
This way you eliminate every special char outside of the alphabet:
def wordsToList(strn):
L = strn.split()
cleanL = []
abc = 'abcdefghijklmnopqrstuvwxyz'
ABC = abc.upper()
letters = abc + ABC
for e in L:
word = ''
for c in e:
if c in letters:
word += c
if word != '':
cleanL.append(word)
return cleanL
s = 'She loves you, yea yea yea! '
L = wordsToList(s)
print(L) # ['She', 'loves', 'you', 'yea', 'yea', 'yea']
I'm not sure if this is fast or optimal or even the right way to program.
nohup some_command &> nohup2.out &
and voila.
Older syntax for Bash version < 4:
nohup some_command > nohup2.out 2>&1 &
If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.
Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.
If you want to audit a client application name along with each failed login, you can use an Extended Events session.
To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/
$query = DB::table('dms_stakeholder_permissions');
$query->select(DB::raw('group_concat(dms_stakeholder_permissions.fid) as fid'),'dms_stakeholder_permissions.rights');
$query->where('dms_stakeholder_permissions.stakeholder_id','4');
$query->orWhere(function($subquery) use ($stakeholderId){
$subquery->where('dms_stakeholder_permissions.stakeholder_id',$stakeholderId);
$subquery->whereIn('dms_stakeholder_permissions.rights',array('1','2','3'));
});
$result = $query->get();
return $result;
// OUTPUT @input $stakeholderId = 1
//select group_concat(dms_stakeholder_permissions.fid) as fid, dms_stakeholder_permissionss
.rights
from dms_stakeholder_permissions
where dms_stakeholder_permissions
.stakeholder_id
= 4 or (dms_stakeholder_permissions
.stakeholder_id
= 1 and dms_stakeholder_permissions
.rights
in (1, 2, 3))
create a libs folder in the inside WEB-INF directory and add jstl, standard jars as below.
I ended up writing a script (I'm trying to teach myself the finer points of bash scripting, so that's why you don't see something like Perl here). It's not exactly a simple affair, but it does most of what I need. It uses Kyle's suggestion for looking up individual users' crontabs, but also deals with /etc/crontab
(including the scripts launched by run-parts
in /etc/cron.hourly
, /etc/cron.daily
, etc.) and the jobs in the /etc/cron.d
directory. It takes all of those and merges them into a display something like the following:
mi h d m w user command
09,39 * * * * root [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm
47 */8 * * * root rsync -axE --delete --ignore-errors / /mirror/ >/dev/null
17 1 * * * root /etc/cron.daily/apt
17 1 * * * root /etc/cron.daily/aptitude
17 1 * * * root /etc/cron.daily/find
17 1 * * * root /etc/cron.daily/logrotate
17 1 * * * root /etc/cron.daily/man-db
17 1 * * * root /etc/cron.daily/ntp
17 1 * * * root /etc/cron.daily/standard
17 1 * * * root /etc/cron.daily/sysklogd
27 2 * * 7 root /etc/cron.weekly/man-db
27 2 * * 7 root /etc/cron.weekly/sysklogd
13 3 * * * archiver /usr/local/bin/offsite-backup 2>&1
32 3 1 * * root /etc/cron.monthly/standard
36 4 * * * yukon /home/yukon/bin/do-daily-stuff
5 5 * * * archiver /usr/local/bin/update-logs >/dev/null
Note that it shows the user, and more-or-less sorts by hour and minute so that I can see the daily schedule.
So far, I've tested it on Ubuntu, Debian, and Red Hat AS.
#!/bin/bash
# System-wide crontab file and cron job directory. Change these for your system.
CRONTAB='/etc/crontab'
CRONDIR='/etc/cron.d'
# Single tab character. Annoyingly necessary.
tab=$(echo -en "\t")
# Given a stream of crontab lines, exclude non-cron job lines, replace
# whitespace characters with a single space, and remove any spaces from the
# beginning of each line.
function clean_cron_lines() {
while read line ; do
echo "${line}" |
egrep --invert-match '^($|\s*#|\s*[[:alnum:]_]+=)' |
sed --regexp-extended "s/\s+/ /g" |
sed --regexp-extended "s/^ //"
done;
}
# Given a stream of cleaned crontab lines, echo any that don't include the
# run-parts command, and for those that do, show each job file in the run-parts
# directory as if it were scheduled explicitly.
function lookup_run_parts() {
while read line ; do
match=$(echo "${line}" | egrep -o 'run-parts (-{1,2}\S+ )*\S+')
if [[ -z "${match}" ]] ; then
echo "${line}"
else
cron_fields=$(echo "${line}" | cut -f1-6 -d' ')
cron_job_dir=$(echo "${match}" | awk '{print $NF}')
if [[ -d "${cron_job_dir}" ]] ; then
for cron_job_file in "${cron_job_dir}"/* ; do # */ <not a comment>
[[ -f "${cron_job_file}" ]] && echo "${cron_fields} ${cron_job_file}"
done
fi
fi
done;
}
# Temporary file for crontab lines.
temp=$(mktemp) || exit 1
# Add all of the jobs from the system-wide crontab file.
cat "${CRONTAB}" | clean_cron_lines | lookup_run_parts >"${temp}"
# Add all of the jobs from the system-wide cron directory.
cat "${CRONDIR}"/* | clean_cron_lines >>"${temp}" # */ <not a comment>
# Add each user's crontab (if it exists). Insert the user's name between the
# five time fields and the command.
while read user ; do
crontab -l -u "${user}" 2>/dev/null |
clean_cron_lines |
sed --regexp-extended "s/^((\S+ +){5})(.+)$/\1${user} \3/" >>"${temp}"
done < <(cut --fields=1 --delimiter=: /etc/passwd)
# Output the collected crontab lines. Replace the single spaces between the
# fields with tab characters, sort the lines by hour and minute, insert the
# header line, and format the results as a table.
cat "${temp}" |
sed --regexp-extended "s/^(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(.*)$/\1\t\2\t\3\t\4\t\5\t\6\t\7/" |
sort --numeric-sort --field-separator="${tab}" --key=2,1 |
sed "1i\mi\th\td\tm\tw\tuser\tcommand" |
column -s"${tab}" -t
rm --force "${temp}"
Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block
or display: inline-block
to transform them:
#whatever:after {
content: "\24B6";
display: inline-block;
transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
Following one is working fine with moments js 2.10 and above
$.fn.dataTableExt.afnFiltering.push(
function( settings, data, dataIndex ) {
var min = $('#min-date').val()
var max = $('#max-date').val()
var createdAt = data[0] || 0; // Our date column in the table
//createdAt=createdAt.split(" ");
var startDate = moment(min, "DD/MM/YYYY");
var endDate = moment(max, "DD/MM/YYYY");
var diffDate = moment(createdAt, "DD/MM/YYYY");
//console.log(startDate);
if (
(min == "" || max == "") ||
(diffDate.isBetween(startDate, endDate))
) { return true; }
return false;
}
);
To get the parameterized build params from the current build from your GroovyScript (using Pipeline), all you need to do is: Say you had a variable called VARNAME.
def myVariable = env.VARNAME
List all containers
docker container ls
List all images
docker image ls
Stop container by container id
docker container stop <container_id>
Remove container by container id
docker container rm <container_id>
If don't want stop and remove, can force remove
docker container rm -f <container_id>
Remove image
docker image rm <image_id>
Done!
Use the Apache Commons library BooleanUtils
class:
String[] values= new String[]{"y","Y","n","N","Yes","YES","yes","no","No","NO","true","false","True","False","TRUE","FALSE",null};
for(String booleanStr : values){
System.out.println("Str ="+ booleanStr +": boolean =" +BooleanUtils.toBoolean(booleanStr));
}
Result:
Str =N: boolean =false
Str =Yes: boolean =true
Str =YES: boolean =true
Str =yes: boolean =true
Str =no: boolean =false
Str =No: boolean =false
Str =NO: boolean =false
Str =true: boolean =true
Str =false: boolean =false
Str =True: boolean =true
Str =False: boolean =false
Str =TRUE: boolean =true
Str =FALSE: boolean =false
Str =null: boolean =false
Android's MVC pattern is (kind-of) implemented with their Adapter classes. They replace a controller with an "adapter." The description for the adapter states:
An Adapter object acts as a bridge between an AdapterView and the underlying data for that view.
I'm just looking into this for an Android application that reads from a database, so I don't know how well it works yet. However, it seems a little like Qt's Model-View-Delegate architecture, which they claim is a step up from a traditional MVC pattern. At least on the PC, Qt's pattern works fairly well.
All above methods are not good because you might change event function name. The easiest is:
btnTest.PerfromClick();
Also seem pdfjam: http://www2.warwick.ac.uk/fac/sci/statistics/staff/academic/firth/software/pdfjam/
This is more an object initialzation question more than a jpa question, both methods work and you can have both of them at the same time , usually if the data member value is ready before the instantiation you use the constructor parameters, if this value could be updated after the instantiation you should have a setter.
You can use array.filter
to return the first item of each distinct value-
var a = [ 1, 5, 1, 6, 4, 5, 2, 5, 4, 3, 1, 2, 6, 6, 3, 3, 2, 4 ];_x000D_
_x000D_
var unique = a.filter(function(itm, i, a) {_x000D_
return i == a.indexOf(itm);_x000D_
});_x000D_
_x000D_
console.log(unique);
_x000D_
If supporting IE8 and below is primary, don't use the unsupported filter
method.
Otherwise,
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun, scope) {
var T = this, A = [], i = 0, itm, L = T.length;
if (typeof fun == 'function') {
while(i < L) {
if (i in T) {
itm = T[i];
if (fun.call(scope, itm, i, T)) A[A.length] = itm;
}
++i;
}
}
return A;
}
}
Is php cross-browser?
(i know, this will make laught many people, but is the more-asked question on php forums!)
In fact, depends what you want to get: - Just the min value:
SELECT MIN(price) FROM pieces
A table (multiples rows) whith the min value: Is as John Woo said above.
But, if can be different rows with same min value, the best is ORDER them from another column, because after or later you will need to do it (starting from John Woo answere):
SELECT * FROM pieces WHERE price = ( SELECT MIN(price) FROM pieces) ORDER BY stock ASC
I have made a small comparison of methods mentioned here.
n = 1e+4
library(microbenchmark)
### Using environment as a container
lPtrAppend <- function(lstptr, lab, obj) {lstptr[[deparse(substitute(lab))]] <- obj}
### Store list inside new environment
envAppendList <- function(lstptr, obj) {lstptr$list[[length(lstptr$list)+1]] <- obj}
microbenchmark(times = 5,
env_with_list_ = {
listptr <- new.env(parent=globalenv())
listptr$list <- NULL
for(i in 1:n) {envAppendList(listptr, i)}
listptr$list
},
c_ = {
a <- list(0)
for(i in 1:n) {a = c(a, list(i))}
},
list_ = {
a <- list(0)
for(i in 1:n) {a <- list(a, list(i))}
},
by_index = {
a <- list(0)
for(i in 1:n) {a[length(a) + 1] <- i}
a
},
append_ = {
a <- list(0)
for(i in 1:n) {a <- append(a, i)}
a
},
env_as_container_ = {
listptr <- new.env(parent=globalenv())
for(i in 1:n) {lPtrAppend(listptr, i, i)}
listptr
}
)
Results:
Unit: milliseconds
expr min lq mean median uq max neval cld
env_with_list_ 188.9023 198.7560 224.57632 223.2520 229.3854 282.5859 5 a
c_ 1275.3424 1869.1064 2022.20984 2191.7745 2283.1199 2491.7060 5 b
list_ 17.4916 18.1142 22.56752 19.8546 20.8191 36.5581 5 a
by_index 445.2970 479.9670 540.20398 576.9037 591.2366 607.6156 5 a
append_ 1140.8975 1316.3031 1794.10472 1620.1212 1855.3602 3037.8416 5 b
env_as_container_ 355.9655 360.1738 399.69186 376.8588 391.7945 513.6667 5 a
Instead of this
df = df[(99 <= df['closing_price'] <= 101)]
You should use this
df = df[(df['closing_price']>=99 ) & (df['closing_price']<=101)]
We have to use NumPy's bitwise Logic operators |, &, ~, ^ for compounding queries. Also, the parentheses are important for operator precedence.
For more info, you can visit the link :Comparisons, Masks, and Boolean Logic
List comps are your friend.
print ", ".join("%.2f" % f for f in list_o_numbers)
Try it:
>>> nums = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999]
>>> print ", ".join("%.2f" % f for f in nums)
9.00, 0.05, 0.03, 0.01
Coverting the first letter of word capital
input:
hello world
String A = hello;
String B = world;
System.out.println(A.toUpperCase().charAt(0)+A.substring(1) + " " + B.toUpperCase().charAt(0)+B.substring(1));
Output:
Hello World
It's the index column, pass pd.to_csv(..., index=False)
to not write out an unnamed index column in the first place, see the to_csv()
docs.
Example:
In [37]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
pd.read_csv(io.StringIO(df.to_csv()))
Out[37]:
Unnamed: 0 a b c
0 0 0.109066 -1.112704 -0.545209
1 1 0.447114 1.525341 0.317252
2 2 0.507495 0.137863 0.886283
3 3 1.452867 1.888363 1.168101
4 4 0.901371 -0.704805 0.088335
compare with:
In [38]:
pd.read_csv(io.StringIO(df.to_csv(index=False)))
Out[38]:
a b c
0 0.109066 -1.112704 -0.545209
1 0.447114 1.525341 0.317252
2 0.507495 0.137863 0.886283
3 1.452867 1.888363 1.168101
4 0.901371 -0.704805 0.088335
You could also optionally tell read_csv
that the first column is the index column by passing index_col=0
:
In [40]:
pd.read_csv(io.StringIO(df.to_csv()), index_col=0)
Out[40]:
a b c
0 0.109066 -1.112704 -0.545209
1 0.447114 1.525341 0.317252
2 0.507495 0.137863 0.886283
3 1.452867 1.888363 1.168101
4 0.901371 -0.704805 0.088335
Came here with the additional requirement, that also parameter/return types should vary. Following Ben Supnik this would be for some type T
typedef T(*binary_T_op)(T, T);
instead of
typedef int(*binary_int_op)(int, int);
The solution here is to put the function type definition and the function template into a surrounding struct template.
template <typename T> struct BinOp
{
typedef T(*binary_T_op )(T, T); // signature for all valid template params
template<binary_T_op op>
T do_op(T a, T b)
{
return op(a,b);
}
};
double mulDouble(double a, double b)
{
return a * b;
}
BinOp<double> doubleBinOp;
double res = doubleBinOp.do_op<&mulDouble>(4, 5);
Alternatively BinOp could be a class with static method template do_op(...), then called as
double res = BinOp<double>::do_op<&mulDouble>(4, 5);
You can use Open Street Map : you will find dozens of different layers and map types, and this is absolutely free. You can download all the map tiles you want. And of course, as anyone can enhance the map, it displays more information than Google's maps. If you need help, you can ask the community which is also very active.
I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.
Easy task using stringByReplacingOccurrencesOfString
NSString *search = [searchbar.text stringByReplacingOccurrencesOfString:@" " withString:@""];
If you are using zsh do the following.
Open .zshrc file nano $HOME/.zshrc
You will see the commented $PATH variable here
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/...
Remove the comment symbol(#) and append your new path using a separator(:) like this.
export PATH=$HOME/bin:/usr/local/bin:/Users/ebin/Documents/Softwares/mongoDB/bin:$PATH
source $HOME/.zshrc
You're done !!!
typedef struct{
char array[4];
}my_array;
my_array array = { .array = {1,1,1,1} }; // initialisation
void assign(my_array a)
{
array.array[0] = a.array[0];
array.array[1] = a.array[1];
array.array[2] = a.array[2];
array.array[3] = a.array[3];
}
char num = 5;
char ber = 6;
int main(void)
{
printf("%d\n", array.array[0]);
// ...
// this works even after initialisation
assign((my_array){ .array = {num,ber,num,ber} });
printf("%d\n", array.array[0]);
// ....
return 0;
}
Note: this answer was motivated by this comment. The purpose of UsedRange
is different from what is mentioned in the answer above.
As to the correct way of finding the last used cell, one has first to decide what is considered used, and then select a suitable method. I conceive at least three meanings:
Used = non-blank, i.e., having data.
Used = "... in use, meaning the section that contains data or formatting." As per official documentation, this is the criterion used by Excel at the time of saving. See also this official documentation. If one is not aware of this, the criterion may produce unexpected results, but it may also be intentionally exploited (less often, surely), e.g., to highlight or print specific regions, which may eventually have no data. And, of course, it is desirable as a criterion for the range to use when saving a workbook, lest losing part of one's work.
Used = "... in use, meaning the section that contains data or formatting" or conditional formatting. Same as 2., but also including cells that are the target for any Conditional Formatting rule.
How to find the last used cell depends on what you want (your criterion).
For criterion 1, I suggest reading this answer.
Note that UsedRange
is cited as unreliable. I think that is misleading (i.e., "unfair" to UsedRange
), as UsedRange
is simply not meant to report the last cell containing data. So it should not be used in this case, as indicated in that answer. See also this comment.
For criterion 2, UsedRange
is the most reliable option, as compared to other options also designed for this use. It even makes it unnecessary to save a workbook to make sure that the last cell is updated.
Ctrl+End will go to a wrong cell prior to saving
(“The last cell is not reset until you save the worksheet”, from
http://msdn.microsoft.com/en-us/library/aa139976%28v=office.10%29.aspx.
It is an old reference, but in this respect valid).
For criterion 3, I do not know any built-in method.
Criterion 2 does not account for Conditional Formatting. One may have formatted cells, based on formulas, which are not detected by UsedRange
or Ctrl+End.
In the figure, the last cell is B3, since formatting was applied explicitly to it. Cells B6:D7 have a format derived from a Conditional Formatting rule, and this is not detected even by UsedRange
.
Accounting for this would require some VBA programming.
As to your specific question: What's the reason behind this?
Your code uses the first cell in your range E4:E48 as a trampoline, for jumping down with End(xlDown)
.
The "erroneous" output will obtain if there are no non-blank cells in your range other than perhaps the first. Then, you are leaping in the dark, i.e., down the worksheet (you should note the difference between blank and empty string!).
Note that:
If your range contains non-contiguous non-blank cells, then it will also give a wrong result.
If there is only one non-blank cell, but it is not the first one, your code will still give you the correct result.
This answer is more meant to explain why, not how. The '=='
operator in R is vectorized in a same way as the '+'
operator. It matches the elements of whatever is on the left side to the elements of whatever is on the right side, per element. For example:
> 1:3 == 1:3
[1] TRUE TRUE TRUE
Here the first test is 1==1
which is TRUE, the second 2==2
and the third 3==3
. Notice that this returns a FALSE in the first and second element because the order is wrong:
> 3:1 == 1:3
[1] FALSE TRUE FALSE
Now if one object is smaller then the other object then the smaller object is repeated as much as it takes to match the larger object. If the size of the larger object is not a multiplication of the size of the smaller object you get a warning that not all elements are repeated. For example:
> 1:2 == 1:3
[1] TRUE TRUE FALSE
Warning message:
In 1:2 == 1:3 :
longer object length is not a multiple of shorter object length
Here the first match is 1==1
, then 2==2
, and finally 1==3
(FALSE) because the left side is smaller. If one of the sides is only one element then that is repeated:
> 1:3 == 1
[1] TRUE FALSE FALSE
The correct operator to test if an element is in a vector is indeed '%in%'
which is vectorized only to the left element (for each element in the left vector it is tested if it is part of any object in the right element).
Alternatively, you can use '&'
to combine two logical statements. '&'
takes two elements and checks elementwise if both are TRUE:
> 1:3 == 1 & 1:3 != 2
[1] TRUE FALSE FALSE
You can do this by subsetting the data you pass into your merge:
merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)
Or you can simply delete the column after your current merge :)
One angle not so far mentioned is tool sets used for editing the code.
Using Visual Studio Code along with the Extension from lukehoban called Go
will do some auto-magic for you. The Go extension automatically runs gofmt
, golint
etc, and removes and adds import
entries. So at least that part is now automatic.
I will admit its not 100% of the solution to the question, but however useful enough.
Link only answers are not considered good practice on StackOverflow, but the advice that is given here should generally NOT be followed up.
I would like to revert to this great answer on a similar question. I quote:
Please stop suggesting to use 777. You're making your file writeable by everyone, which pretty much means you lose all security that the permission system was designed for. If you suggest this, think about the consequences it may have on a poorly configured webserver: it would become incredibly easy to "hack" the website, by overwriting the files. So, don't.
Since Python 3.6, there's a solution for this in Python's standard library, namely random.choices
.
Example usage: let's set up a population and weights matching those in the OP's question:
>>> from random import choices
>>> population = [1, 2, 3, 4, 5, 6]
>>> weights = [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]
Now choices(population, weights)
generates a single sample:
>>> choices(population, weights)
4
The optional keyword-only argument k
allows one to request more than one sample at once. This is valuable because there's some preparatory work that random.choices
has to do every time it's called, prior to generating any samples; by generating many samples at once, we only have to do that preparatory work once. Here we generate a million samples, and use collections.Counter
to check that the distribution we get roughly matches the weights we gave.
>>> million_samples = choices(population, weights, k=10**6)
>>> from collections import Counter
>>> Counter(million_samples)
Counter({5: 399616, 6: 200387, 4: 200117, 1: 99636, 3: 50219, 2: 50025})
\d{1,2}[,.]\d{1,2}
\d means a digit, the {1,2} part means 1 or 2 of the previous character (\d in this case) and the [,.] part means either a comma or dot.
With recent browsers you can use the HTML5 download attribute as well:
<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>
It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):
(function (){
addEvent(window, "load", function (){
if (isInternetExplorer())
polyfillDataUriDownload();
});
function polyfillDataUriDownload(){
var links = document.querySelectorAll('a[download], area[download]');
for (var index = 0, length = links.length; index<length; ++index) {
(function (link){
var dataUri = link.getAttribute("href");
var fileName = link.getAttribute("download");
if (dataUri.slice(0,5) != "data:")
throw new Error("The XHR part is not implemented here.");
addEvent(link, "click", function (event){
cancelEvent(event);
try {
var dataBlob = dataUriToBlob(dataUri);
forceBlobDownload(dataBlob, fileName);
} catch (e) {
alert(e)
}
});
})(links[index]);
}
}
function forceBlobDownload(dataBlob, fileName){
window.navigator.msSaveBlob(dataBlob, fileName);
}
function dataUriToBlob(dataUri) {
if (!(/base64/).test(dataUri))
throw new Error("Supports only base64 encoding.");
var parts = dataUri.split(/[:;,]/),
type = parts[1],
binData = atob(parts.pop()),
mx = binData.length,
uiArr = new Uint8Array(mx);
for(var i = 0; i<mx; ++i)
uiArr[i] = binData.charCodeAt(i);
return new Blob([uiArr], {type: type});
}
function addEvent(subject, type, listener){
if (window.addEventListener)
subject.addEventListener(type, listener, false);
else if (window.attachEvent)
subject.attachEvent("on" + type, listener);
}
function cancelEvent(event){
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
function isInternetExplorer(){
return /*@cc_on!@*/false || !!document.documentMode;
}
})();
Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:
Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.
Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.
If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as
static final int NUM_GEARS = 6
, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.
Got this error on eclipse IDE version 4.10, Spring boot 2.2.0.M4, changed the Spring boot version to 2.2.0.M2 (after many other solutions recommended and it solved the error). Maybe something missing or broken in the latest version of Spring boot starter project module maven POM.
Why not just use
@Html.DisplayFor(model => model.Control.PeriodType)
Try the following code to display scroll bar always on your page,
::-webkit-scrollbar {
-webkit-appearance: none;
width: 10px;
}
::-webkit-scrollbar-thumb {
border-radius: 5px;
background-color: rgba(0,0,0,.5);
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
this will always show the vertical and horizontal scroll bar on your page. If you need only a vertical scroll bar then put overflow-x: hidden
$('input[type="button"]').click(function (e) {
if (e.target) {
alert(e.target.id + ' clicked');
}
});
you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.
The semantics of Having
To better understand having, you need to see it from a theoretical point of view.
A group by is a query that takes a table and summarizes it into another table. You summarize the original table by grouping the original table into subsets (based upon the attributes that you specify in the group by). Each of these groups will yield one tuple.
The Having is simply equivalent to a WHERE clause after the group by has executed and before the select part of the query is computed.
Lets say your query is:
select a, b, count(*)
from Table
where c > 100
group by a, b
having count(*) > 10;
The evaluation of this query can be seen as the following steps:
You can extend this to any complex query there Table can be any complex query that return a table (a cross product, a join, a UNION, etc).
In fact, having is syntactic sugar and does not extend the power of SQL. Any given query:
SELECT list
FROM table
GROUP BY attrList
HAVING condition;
can be rewritten as:
SELECT list from (
SELECT listatt
FROM table
GROUP BY attrList) as Name
WHERE condition;
The listatt is a list that includes the GROUP BY attributes and the expressions used in list and condition. It might be necessary to name some expressions in this list (with AS). For instance, the example query above can be rewritten as:
select a, b, count
from (select a, b, count(*) as count
from Table
where c > 100
group by a, b) as someName
where count > 10;
The solution you need
Your solution seems to be correct:
SELECT s.sid, s.name
FROM Supplier s, Supplies su, Project pr
WHERE s.sid = su.sid AND su.jid = pr.jid
GROUP BY s.sid, s.name
HAVING COUNT (DISTINCT pr.jid) >= 2
You join the three tables, then using sid as a grouping attribute (sname is functionally dependent on it, so it does not have an impact on the number of groups, but you must include it, otherwise it cannot be part of the select part of the statement). Then you are removing those that do not satisfy your condition: the satisfy pr.jid is >= 2
, which is that you wanted originally.
Best solution to your problem
I personally prefer a simpler cleaner solution:
SELECT sid, sname from
(SELECT sid from supplies
GROUP BY sid, pid
HAVING count(DISTINCT jid) >= 2
) AS T1
NATURAL JOIN
Supliers;
It will also be faster to execute, because the join is only done when needed, not all the times.
--dmg
EDIT: as of Java8 you'd better use Files
class:
Path resultingPath = Files.createDirectories('A/B');
I don't know if this ultimately fixes your problem but class File
has method mkdirs()
which fully creates the path specified by the file.
File f = new File("/A/B/");
f.mkdirs();
If you are using zsh
on an OS X, you have to edit the zshrc file.
Use vim or your favorite text editor to open zshrc file:
vim ~/.zshrc
Paste the path to adb
in this file:
export PATH="/Users/{$USER}/Library/Android/sdk/platform-tools":$PATH
I want to do this:
print("Hello"[1...3])
// out: Error
But unfortunately, I can't write a subscript of my own because the loathed one takes up the name space.
We can do this however:
print("Hello"[range: 1...3])
// out: ell
Just add this to your project:
extension String {
subscript(range: ClosedRange<Int>) -> String {
get {
let start = String.Index(utf16Offset: range.lowerBound, in: self)
let end = String.Index(utf16Offset: range.upperBound, in: self)
return String(self[start...end])
}
}
}
You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)
If you pass $element
into a controller, like you would $scope
, you can use its find()
function. Note that, in the jQueryLite included in Angular, find()
will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find()
can be used, including finding by attribute.
So, for this HTML:
<div ng-controller='MyCtrl'>
<div>
<div name='foo' class='myElementClass'>this one</div>
</div>
</div>
This AngularJS code should work:
angular.module('MyClient').controller('MyCtrl', [
'$scope',
'$element',
'$log',
function ($scope, $element, $log) {
// Find the element by its class attribute, within your controller's scope
var myElements = $element.find('.myElementClass');
// myElements is now an array of jQuery DOM elements
if (myElements.length == 0) {
// Not found. Are you sure you've included the full jQuery?
} else {
// There should only be one, and it will be element 0
$log.debug(myElements[0].name); // "foo"
}
}
]);
T = map(lambda i: L[i], Idx)
You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.
System.out.printf("%2d. %-20s $%.2f%n", i + 1, BOOK_TYPE[i], COST[i]);
Format String Syntax: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
Formatting Numeric Print Output: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.
It has already been explained that calling system.gc()
may do nothing, and that any code that "needs" the garbage collector to run is broken.
However, the pragmatic reason that it is bad practice to call System.gc()
is that it is inefficient. And in the worst case, it is horribly inefficient! Let me explain.
A typical GC algorithm identifies garbage by traversing all non-garbage objects in the heap, and inferring that any object not visited must be garbage. From this, we can model the total work of a garbage collection consists of one part that is proportional to the amount of live data, and another part that is proportional to the amount of garbage; i.e. work = (live * W1 + garbage * W2)
.
Now suppose that you do the following in a single-threaded application.
System.gc(); System.gc();
The first call will (we predict) do (live * W1 + garbage * W2)
work, and get rid of the outstanding garbage.
The second call will do (live* W1 + 0 * W2)
work and reclaim nothing. In other words we have done (live * W1)
work and achieved absolutely nothing.
We can model the efficiency of the collector as the amount of work needed to collect a unit of garbage; i.e. efficiency = (live * W1 + garbage * W2) / garbage
. So to make the GC as efficient as possible, we need to maximize the value of garbage
when we run the GC; i.e. wait until the heap is full. (And also, make the heap as big as possible. But that is a separate topic.)
If the application does not interfere (by calling System.gc()
), the GC will wait until the heap is full before running, resulting in efficient collection of garbage1. But if the application forces the GC to run, the chances are that the heap won't be full, and the result will be that garbage is collected inefficiently. And the more often the application forces GC, the more inefficient the GC becomes.
Note: the above explanation glosses over the fact that a typical modern GC partitions the heap into "spaces", the GC may dynamically expand the heap, the application's working set of non-garbage objects may vary and so on. Even so, the same basic principal applies across the board to all true garbage collectors2. It is inefficient to force the GC to run.
1 - This is how the "throughput" collector works. Concurrent collectors such as CMS and G1 use different criteria to decide when to start the garbage collector.
2 - I'm also excluding memory managers that use reference counting exclusively, but no current Java implementation uses that approach ... for good reason.
URL url = getClass().getClassLoader().getResource("someresource.xxx");
That should do it.
HTML5 element can give dotted underline so the beneath text will have dotted line rather than regular underline. And the title attribute creates a tool tip for the user when they hover their cursor over the element:
NOTE: The dotted border/underline is shown by default in Firefox and Opera, but IE8, Safari, and Chrome need a line of CSS:
<abbr title="Hyper Text Markup Language">HTML</abbr>
I set my width element, with javascript. After I set the de vh.
html
<div id="gifimage"><img src="back_phone_back.png" style="width: 100%"></div>
css
#gifimage {
position: absolute;
height: 70vh;
}
javascript
imageHeight = document.getElementById('gifimage').clientHeight;
// if (isMobile)
document.getElementById('gifimage').setAttribute("style","height:" + imageHeight + "px");
This works for me. I don't use jquery ect. because I want it to load as soon as posible.
in your view:
<?php $value = '<p id="course_id"></p>';?>
javascript code:
var course = document.getElementById("courses").value;
document.getElementById("course_id").innerHTML = course;
The limit is not 2g or 3gb its 4gb for 32bit.
The reason people think its 3gb is that the OS shows 3gb free when they really have 4gb of system ram.
Its total RAM of 4gb. So if you have a 1 gb video card that counts as part of the total ram viewed by the 32bit OS.
4Gig not 3 not 2 got it?
This works if you want the element to span across the page like another navigation bar.
width: calc (width: 100% - width whatever else is off centering it)
For example if your side navigation bar is 200px:
width: calc(100% - 200px);
Your LMSInitialize
function is declared inside Scorm_API_12
function. So it can be seen only in Scorm_API_12
function's scope.
If you want to use this function like API.LMSInitialize("")
, declare Scorm_API_12
function like this:
function Scorm_API_12() {
var Initialized = false;
this.LMSInitialize = function(param) {
errorCode = "0";
if (param == "") {
if (!Initialized) {
Initialized = true;
errorCode = "0";
return "true";
} else {
errorCode = "101";
}
} else {
errorCode = "201";
}
return "false";
}
// some more functions, omitted.
}
var API = new Scorm_API_12();
strtok
doesn't change the parameter itself (str
). It stores that pointer (in a local static variable). It can then change what that parameter points to in subsequent calls without having the parameter passed back. (And it can advance that pointer it has kept however it needs to perform its operations.)
From the POSIX strtok
page:
This function uses static storage to keep track of the current string position between calls.
There is a thread-safe variant (strtok_r
) that doesn't do this type of magic.
int add(int x, int y); // forward declaration using function prototype
Can you explain "forward declaration" more further? What is the problem if we use it in the main() function?
It's same as #include"add.h"
. If you know,preprocessor expands the file which you mention in #include
, in the .cpp file where you write the #include
directive. That means, if you write #include"add.h"
, you get the same thing, it is as if you doing "forward declaration".
I'm assuming that add.h
has this line:
int add(int x, int y);
Generically, you can use a custom font using @font-face
in your CSS. Here's a very basic example:
@font-face {
font-family: 'YourFontName'; /*a name to be used later*/
src: url('http://domain.com/fonts/font.ttf'); /*URL to font*/
}
Then, trivially, to use the font on a specific element:
.classname {
font-family: 'YourFontName';
}
(.classname
is your selector).
Note that certain font-formats don't work on all browsers; you can use fontsquirrel.com's generator to avoid too much effort converting.
You can find a nice set of free web-fonts provided by Google Fonts (also has auto-generated CSS @font-face
rules, so you don't have to write your own).
while also preventing people from having free access to download the font, if possible
Nope, it isn't possible to style your text with a custom font embedded via CSS, while preventing people from downloading it. You need to use images, Flash, or the HTML5 Canvas, all of which aren't very practical.
I hope that helped!
Aside from the ones you mention, I only use frequently when diffing the following:
:diffupdate
:diffu
-> recalculate the diff, useful when after making several changes vim's isn't showing minimal changes anymore. Note that it only works if the files have been modified inside vimdiff. Otherwise, use:
:e
to reload the files if they have been modified outside of vimdiff. :set noscrollbind
-> temporarily disable simultaneous scrolling on both buffers, reenable by :set scrollbind
and scrolling.Most of what you asked for is folding: vim user manual's chapter on folding. Outside of diffs I sometime use:
zo
-> open fold.zc
-> close fold.But you'll probably be better served by:
zr
-> reducing folding level.zm
-> one more folding level, please.or even:
zR
-> Reduce completely the folding, I said!.zM
-> fold Most!.The other thing you asked for, use n lines of folding, can be found at the vim reference manual section on options, via the section on diff:
set diffopt=<TAB>
, then update or add context:n
.You should also take a look at the user manual section on diff.
if you need to overwrite the admin/index.html
, you can set the index_template parameter of the AdminSite
.
e.g.
# urls.py
...
from django.contrib import admin
admin.site.index_template = 'admin/my_custom_index.html'
admin.autodiscover()
and place your template in <appname>/templates/admin/my_custom_index.html
If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.
First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.
I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http
service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.
app.factory('locations', function($http) {
var promise = null;
return function() {
if (promise) {
// If we've already asked for this data once,
// return the promise that already exists.
return promise;
} else {
promise = $http.get('locations/locations.json');
return promise;
}
};
});
As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations
service into the directive, but this couples the directive to that service.
A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.
In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.
app.controller('SomeController', function($scope, locations) {
locations().success(function(data) {
$scope.locations = data;
});
});
<ul class="list">
<li ng-repeat="location in locations">
<a href="#">{{location.id}}. {{location.name}}</a>
</li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
scope: {
// creates a scope variable in your directive
// called `locations` bound to whatever was passed
// in via the `locations` attribute in the DOM
locations: '=locations'
},
link: function(scope, element, attrs) {
scope.$watch('locations', function(locations) {
angular.forEach(locations, function(location, key) {
// do something
});
});
}
};
});
In this way, the map
directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.
As of jsdom v10, .env() function is deprecated. I did it like below after trying a lot of things to require jquery:
var jsdom = require('jsdom');_x000D_
const { JSDOM } = jsdom;_x000D_
const { window } = new JSDOM();_x000D_
const { document } = (new JSDOM('')).window;_x000D_
global.document = document;_x000D_
_x000D_
var $ = jQuery = require('jquery')(window);
_x000D_
Hope this helps you or anyone who has been facing these types of issues.
For Android Studio 3.1 & above, the distributionUrl
has been updated to version 4.6 from version 4.4. Your gradle-wrapper.properties
should look like this:
#DATE
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
For Android Studio 3.0 & above, the distributionUrl
has been updated to version 4.1 from version 3.3. Your gradle-wrapper.properties
should look like this:
#DATE
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
#DATE
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
In your Laravel deployment it would be
/vendor/laravel/framework/src/Illuminate/Foundation/Application.php
to see who changed your Laravel version look at what's defined in composer.json. If you have "laravel/framework": "5.4.*", then it will update to the latest after composer update is run. Composer.lock is the file that results from running a composer update, so really see who last one to modify the composer.json file was (hopefully you have that in version control). You can read more about it here https://getcomposer.org/doc/01-basic-usage.md
The below is a little slow, but it gives a nicely formatted list of packages that pip
is aware of. That is to say, not all of them were installed "by" pip, but all of them should be able to be upgraded by pip.
$ pip search . | egrep -B1 'INSTALLED|LATEST'
The reason it is slow is that it lists the contents of the entire pypi repo. I filed a ticket suggesting pip list
provide similar functionality but more efficiently.
Sample output: (restricted the search to a subset instead of '.' for all.)
$ pip search selenium | egrep -B1 'INSTALLED|LATEST'
selenium - Python bindings for Selenium
INSTALLED: 2.24.0
LATEST: 2.25.0
--
robotframework-selenium2library - Web testing library for Robot Framework
INSTALLED: 1.0.1 (latest)
$
The reason can be not adding "annotation-driven" in your dispatcher servlet xml file. and also it may be due to not adding as application/json in the headers
This is how I actually do it, for p pairs of socks (n = 2p individual socks):
The worst-case scenario of this scheme is that every pair of socks is different enough that it must be matched exactly, and that the first n/2 socks you pick are all different. This is your O(n2) scenario, and it's extremely unlikely. If the number of unique types of sock t is less than the number of pairs p = n/2, and the socks in each type are alike enough (usually in wear-related terms) that any sock of that type can be paired with any other, then as I inferred above, the maximum number of socks you will ever have to compare to is t, after which the next one you pull will match one of the unpaired socks. This scenario is much more likely in the average sock drawer than the worst-case, and reduces the worst-case complexity to O(n*t) where usually t << n.
Surround your %1
with something.
Eg:
if not "%1" == ""
Another one I've seen fairly often:
if not {%1} == {}
And so on...
The problem, as you can likely guess, is that the %1
is literally replaced with emptiness. It is not 'an empty string' it is actually a blank spot in your source file at that point.
Then after the replacement, the interpreter tries to parse the if
statement and gets confused.
oldDate
is not in the format of the SimpleDateFormat
you are using to parse it.
Try this format: dd-MMM-yyyy
- It matches what you're trying to parse.
Just add the unique key to the your Components
data.map((marker)=>{
return(
<YourComponents
key={data.id} // <----- unique key
/>
);
})
The exception occurs due to this statement,
called_from.equalsIgnoreCase("add")
It seem that the previous statement
String called_from = getIntent().getStringExtra("called");
returned a null reference.
You can check whether the intent to start this activity contains such a key "called".
'It' requires a dll file called cvextern.dll . 'It' can be either your own cs file or some other third party dll which you are using in your project.
To call native dlls to your own cs file, copy the dll into your project's root\lib directory and add it as an existing item. (Add -Existing item) and use Dllimport with correct location.
For third party , copy the native library to the folder where the third party library resides and add it as an existing item.
After building make sure that the required dlls are appearing in Build folder. In some cases it may not appear or get replaced in Build folder. Delete the Build folder manually and build again.
I can't say it's an appropriate solution but you can try this.
Steps
This is just a hack solution if you want to maintain the history and don't to create mass in it.
If you don't want to use this solution please kindly ignore and try to avoid devote it. Because I am really trying to increase my score on this side
This might be easier to explain with a sample dataset.
Create Sample Data
Let's assume we have a single column of Timestamps, date
and another column we would like to perform an aggregation on, a
.
df = pd.DataFrame({'date':pd.DatetimeIndex(['2012-1-1', '2012-6-1', '2015-1-1', '2015-2-1', '2015-3-1']),
'a':[9,5,1,2,3]}, columns=['date', 'a'])
df
date a
0 2012-01-01 9
1 2012-06-01 5
2 2015-01-01 1
3 2015-02-01 2
4 2015-03-01 3
There are several ways to group by year
year
propertydate
in index and use anonymous function to access yearresample
method.dt
accessor with year
propertyWhen you have a column (and not an index) of pandas Timestamps, you can access many more extra properties and methods with the dt
accessor. For instance:
df['date'].dt.year
0 2012
1 2012
2 2015
3 2015
4 2015
Name: date, dtype: int64
We can use this to form our groups and calculate some aggregations on a particular column:
df.groupby(df['date'].dt.year)['a'].agg(['sum', 'mean', 'max'])
sum mean max
date
2012 14 7 9
2015 6 2 3
If you set the date column as the index, it becomes a DateTimeIndex with the same properties and methods as the dt
accessor gives normal columns
df1 = df.set_index('date')
df1.index.year
Int64Index([2012, 2012, 2015, 2015, 2015], dtype='int64', name='date')
Interestingly, when using the groupby method, you can pass it a function. This function will be implicitly passed the DataFrame's index. So, we can get the same result from above with the following:
df1.groupby(lambda x: x.year)['a'].agg(['sum', 'mean', 'max'])
sum mean max
2012 14 7 9
2015 6 2 3
resample
methodIf your date column is not in the index, you must specify the column with the on
parameter. You also need to specify the offset alias as a string.
df.resample('AS', on='date')['a'].agg(['sum', 'mean', 'max'])
sum mean max
date
2012-01-01 14.0 7.0 9.0
2013-01-01 NaN NaN NaN
2014-01-01 NaN NaN NaN
2015-01-01 6.0 2.0 3.0
You can also convert the date column to a pandas Period object. We must pass in the offset alias as a string to determine the length of the Period.
df['date'].dt.to_period('A')
0 2012
1 2012
2 2015
3 2015
4 2015
Name: date, dtype: object
We can then use this as a group
df.groupby(df['date'].dt.to_period('Y'))['a'].agg(['sum', 'mean', 'max'])
sum mean max
2012 14 7 9
2015 6 2 3
When you don't give a prototype for the function before using it, C assumes that it takes any number of parameters and returns an int. So when you first try to use do_something, that's the type of function the compiler is looking for. Doing this should produce a warning about an "implicit function declaration".
So in your case, when you actually do declare the function later on, C doesn't allow function overloading, so it gets pissy because to it you've declared two functions with different prototypes but with the same name.
Short answer: declare the function before trying to use it.
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
jQuery(document).on('click', 'video', function(){
if (this.paused) {
this.play();
} else {
this.pause();
}
});
As rebenvp said I used:
g++ *.cpp -o output
And then do this for output:
./output
But a better solution is to use make
file. Read here to know more about make
files.
Also make sure that you have added the required .h
files in the .cpp
files.
You can use the very flexible solution flexbox to your Bootstrap.
justify-content: center;
can center your column.
Check out flex.
When dealing with the HTML DOM (ie. this
), the array selector [0]
must be used to retrieve the jQuery element from the Javascript array.
$(this)[0].getAttribute('src');
I enabled zlib.output_compression
in php.ini
and it seemed to fix the issue for me.
This method can be useful to validate date in PHP. Current method is for mm/dd/yyyy format. You have to update parameter sequence in checkdate as per your format and delimiter in explode .
function isValidDate($dt)
{
$dtArr = explode('/', $dt);
if (!empty($dtArr[0]) && !empty($dtArr[1]) && !empty($dtArr[2])) {
return checkdate((int) $dtArr[0], (int) $dtArr[1], (int) $dtArr[2]);
} else {
return false;
}
}
You must set up proper encoding and collation for your tables.
Table encoding must reflect the actual data encoding. What is your data encoding?
To see table encoding, you can run a query SHOW CREATE TABLE tablename
var filename = fullPath.replace(/^.*[\\\/]/, '')
This will handle both \ OR / in paths
I can't think of anything that would be able to handle this out of the box. But it's fairly well handled for floating point numbers.
>>> round(1.2322, 2)
1.23
Integers are trickier. They're not stored as base 10 in memory, so significant places isn't a natural thing to do. It's fairly trivial to implement once they're a string though.
Or for integers:
>>> def intround(n, sigfigs):
... n = str(n)
... return n[:sigfigs] + ('0' * (len(n)-(sigfigs)))
>>> intround(1234, 1)
'1000'
>>> intround(1234, 2)
If you would like to create a function that handles any number, my preference would be to convert them both to strings and look for a decimal place to decide what to do:
>>> def roundall1(n, sigfigs):
... n = str(n)
... try:
... sigfigs = n.index('.')
... except ValueError:
... pass
... return intround(n, sigfigs)
Another option is to check for type. This will be far less flexible, and will probably not play nicely with other numbers such as Decimal
objects:
>>> def roundall2(n, sigfigs):
... if type(n) is int: return intround(n, sigfigs)
... else: return round(n, sigfigs)
:: short answer :
:: perl -MCPAN -e "install PAR::Packer"
pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>>
:: long answer - create the following cmd , adjust vars to your taste ...
:: next_line_is_templatized
:: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
:: disable the echo
@echo off
:: this is part of the name of the file - not used
set _Action=run
:: the name of the Product next_line_is_templatized
set _ProductName=morphus
:: the version of the current Product next_line_is_templatized
set _ProductVersion=1.2.3
:: could be dev , test , dev , prod next_line_is_templatized
set _ProductType=dev
:: who owns this Product / environment next_line_is_templatized
set _ProductOwner=ysg
:: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )
set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%
:: go the run dir
cd %~dp0
:: do 4 times going up
for /L %%i in (1,1,5) do pushd ..
:: The BaseDir is 4 dirs up than the run dir
set _ProductBaseDir=%CD%
:: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
:: remove the trailing \
IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
:: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
:: debug pause
:: The version directory of the Product
set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%
:: the dir under which all the perl scripts are placed
set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl
:: The Perl script performing all the tasks
set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl
:: where the log events are stored
set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log
:: define a favorite editor
set _MyEditor=textpad
ECHO Check the variables
set _
:: debug PAUSE
:: truncate the run log
echo date is %date% time is %time% > %_RunLog%
:: uncomment this to debug all the vars
:: debug set >> %_RunLog%
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: now open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: this is the call without debugging
:: old
echo CFPoint1 OK The run cmd script %0 is executed >> %_RunLog%
echo CFPoint2 OK compile the exe file STDOUT and STDERR to a single _RunLog file >> %_RunLog%
cd %_ProductVersionPerlDir%
pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1
:: open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: uncomment this line to wait for 5 seconds
:: ping localhost -n 5
:: uncomment this line to see what is happening
:: PAUSE
::
:::::::
:: Purpose:
:: To compile every *.pl file into *.exe file under a folder
:::::::
:: Requirements :
:: perl , pp , win gnu utils tee
:: perl -MCPAN -e "install PAR::Packer"
:: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
:::::::
:: VersionHistory
:: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
:::::::
:: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
It's your "fault" in that that's how Or
is defined, so it's the behaviour you should expect:
In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.
But you don't have to endure it. You can use OrElse
to get short-circuiting behaviour.
So you probably want:
If (example Is Nothing OrElse Not example.Item = compare.Item) Then
'Proceed
End If
I can't say it reads terribly nicely, but it should work...
CREATE TRIGGER dbo.TableName_IUD
ON dbo.TableName
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
--
-- Check if this is an INSERT, UPDATE or DELETE Action.
--
DECLARE @action as char(1);
SET @action = 'I'; -- Set Action to Insert by default.
IF EXISTS(SELECT * FROM DELETED)
BEGIN
SET @action =
CASE
WHEN EXISTS(SELECT * FROM INSERTED) THEN 'U' -- Set Action to Updated.
ELSE 'D' -- Set Action to Deleted.
END
END
ELSE
IF NOT EXISTS(SELECT * FROM INSERTED) RETURN; -- Nothing updated or inserted.
...
END
RDDs extend the Serialisable interface, so this is not what's causing your task to fail. Now this doesn't mean that you can serialise an RDD
with Spark and avoid NotSerializableException
Spark is a distributed computing engine and its main abstraction is a resilient distributed dataset (RDD), which can be viewed as a distributed collection. Basically, RDD's elements are partitioned across the nodes of the cluster, but Spark abstracts this away from the user, letting the user interact with the RDD (collection) as if it were a local one.
Not to get into too many details, but when you run different transformations on a RDD (map
, flatMap
, filter
and others), your transformation code (closure) is:
You can of course run this locally (as in your example), but all those phases (apart from shipping over network) still occur. [This lets you catch any bugs even before deploying to production]
What happens in your second case is that you are calling a method, defined in class testing
from inside the map function. Spark sees that and since methods cannot be serialized on their own, Spark tries to serialize the whole testing
class, so that the code will still work when executed in another JVM. You have two possibilities:
Either you make class testing serializable, so the whole class can be serialized by Spark:
import org.apache.spark.{SparkContext,SparkConf}
object Spark {
val ctx = new SparkContext(new SparkConf().setAppName("test").setMaster("local[*]"))
}
object NOTworking extends App {
new Test().doIT
}
class Test extends java.io.Serializable {
val rddList = Spark.ctx.parallelize(List(1,2,3))
def doIT() = {
val after = rddList.map(someFunc)
after.collect().foreach(println)
}
def someFunc(a: Int) = a + 1
}
or you make someFunc
function instead of a method (functions are objects in Scala), so that Spark will be able to serialize it:
import org.apache.spark.{SparkContext,SparkConf}
object Spark {
val ctx = new SparkContext(new SparkConf().setAppName("test").setMaster("local[*]"))
}
object NOTworking extends App {
new Test().doIT
}
class Test {
val rddList = Spark.ctx.parallelize(List(1,2,3))
def doIT() = {
val after = rddList.map(someFunc)
after.collect().foreach(println)
}
val someFunc = (a: Int) => a + 1
}
Similar, but not the same problem with class serialization can be of interest to you and you can read on it in this Spark Summit 2013 presentation.
As a side note, you can rewrite rddList.map(someFunc(_))
to rddList.map(someFunc)
, they are exactly the same. Usually, the second is preferred as it's less verbose and cleaner to read.
EDIT (2015-03-15): SPARK-5307 introduced SerializationDebugger and Spark 1.3.0 is the first version to use it. It adds serialization path to a NotSerializableException. When a NotSerializableException is encountered, the debugger visits the object graph to find the path towards the object that cannot be serialized, and constructs information to help user to find the object.
In OP's case, this is what gets printed to stdout:
Serialization stack:
- object not serializable (class: testing, value: testing@2dfe2f00)
- field (class: testing$$anonfun$1, name: $outer, type: class testing)
- object (class testing$$anonfun$1, <function1>)
viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.
However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView ...>
<LinearLayout ...>
...
...
</LinearLayout>
</ScrollView>
You should in fact URI-encode the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes /
should be taken into account and which not. You cannot predict that on a raw String
beforehand. The problem really needs to be solved at a higher level. Where does that String
come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.
At any way, if you can ensure that it are only the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with %20
:
URI uri = new URI(string.replace(" ", "%20"));
Or if you can ensure that it's only the part after the last slash which needs to be URI-encoded, then you can also just do so with help of android.net.Uri
utility class:
int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + Uri.encode(string.substring(pos)));
Do note that URLEncoder
is insuitable for the task as it's designed to encode query string parameter names/values as per application/x-www-form-urlencoded
rules (as used in HTML forms). See also Java URL encoding of query string parameters.
Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:
Delivery -> Package (One -> Many)
CREATE TABLE Delivery(
Id INT IDENTITY PRIMARY KEY,
NoteNumber NVARCHAR(255) NOT NULL
)
CREATE TABLE Package(
Id INT IDENTITY PRIMARY KEY,
Status INT NOT NULL DEFAULT 0,
Delivery_Id INT NOT NULL,
CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)
The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).
So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
Browser > Inspect > Element >
<.app-root _nghost-hey-c0="" ng-version="8.2.11">
In terminal
:> ng version
:> ng --version
:> ng -v
Put http.request.method == "POST"
in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.
The example code does not throw an NPE. (there also should not be a ';' behind the i++)
Visually you can open "SQL Server Configuration Manager" and check properties of "Network Configuration":
it is safer to use the method compareTo()
BigDecimal a = new BigDecimal(10);
BigDecimal b = BigDecimal.ZERO;
System.out.println(" result ==> " + a.compareTo(b));
console print
result ==> 1
compareTo()
returns
- 1 if a is greater than b
- -1 if b is less than b
- 0 if a is equal to b
now for your problem you can use
if (value.compareTo(BigDecimal.ZERO) > 0)
or
if (value.compareTo(new BigDecimal(0)) > 0)
I hope it helped you.
The problem is that the timer
variable is local, and its value is lost after each function call.
You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:
var endAndStartTimer = (function () {
var timer; // variable persisted here
return function () {
window.clearTimeout(timer);
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
};
})();
You can set up logrotate to clear the logs periodically.
Example file in /etc/logrotate.d/docker-logs
/var/lib/docker/containers/*/*.log {
rotate 7
daily
compress
size=50M
missingok
delaycompress
copytruncate
}
move
in windows is equivalent of mv
command in Linux
del
in windows is equivalent of rm
command in Linux
The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.
That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!
<style>
html, body {
height: 100%;
}
#tableContainer-1 {
height: 100%;
width: 100%;
display: table;
}
#tableContainer-2 {
vertical-align: middle;
display: table-cell;
height: 100%;
}
#myTable {
margin: 0 auto;
}
</style>
<div id="tableContainer-1">
<div id="tableContainer-2">
<table id="myTable" border>
<tr><td>Name</td><td>J W BUSH</td></tr>
<tr><td>Proficiency</td><td>PHP</td></tr>
<tr><td>Company</td><td>BLAH BLAH</td></tr>
</table>
</div>
</div>
What you could do is use ng-repeat
passing in the value of whatever you're iterating on to the ng-checked
and from there utilising ng-class
to apply your styles depending on the result.
I did something similar recently and it worked for me.
This marks the session as Abandoned, but the session won't actually be Abandoned at that moment, the request has to complete first.
I didn't want to wrap my *ngFor
into another div
with *ngIf
or use [ngClass]
, so I created a pipe named show
:
show.pipe.ts
export class ShowPipe implements PipeTransform {
transform(values: any[], show: boolean): any[] {
if (!show) {
return[];
}
return values;
}
}
any.page.html
<table>
<tr *ngFor="let arr of anyArray | show : ngIfCondition">
<td>{{arr.label}}</td>
</tr>
</table>
You can try intersection()
and subtract()
methods from CollectionUtils
.
intersection()
method gives you a collection containing common elements and the subtract()
method gives you all the uncommon ones.
They should also take care of similar elements
it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit
if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte
when in doubt, use VARCHAR2(1 CHAR)
same thing answered here Difference between BYTE and CHAR in column datatypes
Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB
in Oracle, don't use VARCHAR