As of Notepad++ version 7.5, plugin manager is no longer shipped with Notepad++
From the Notepad++ release notes:
You may notice that Plugin Manager plugin has been removed from the official distribution. The reason is Plugin Manager contains the advertising in its dialog. I hate Ads in applications, and I ensure you that there was no, and there will never be Ads in Notepad++.
A built-in Plugin Manager is in progress, and I will do my best to ship it with Notepad++ ASAP.
If the above doesn't put you off, and you want to proceed and install the plugin manager anyway, it looks like there's a GitHub repository for nppPluginManager - though I haven't personally used it, so cannot comment on it's validity.
The nppPluginManager installation instructions state:
To install the plugin manager, simply download (links below) the .zip, and place the PluginManager.dll file in the Notepad++ plugins directory, and the gpup.exe in the updater directory under your Notepad++ program directory. (e.g. "C:\Program Files\Notepad++\updater")
In fact, if you prefer, you can just add the PluginManager.dll to the plugins directory, then do a reinstall of Plugin Manager from the plugin itself, which will place the file in the right place! Of course, if you're already using an earlier version of the plugin manager, you'll be able to just update from the update tab (or when you get the notification that the update has happened).
The GitHub repository also contains the latest release.
I had the same issue and I could solve it like this:
1) If your minSdkVersion
is set to 21 or a higher value, the only thing you need to do is to set multiDexEnabled
in your build.gradle
file at the module level, as shown below:
android {
defaultConfig {
...
minSdkVersion 21
targetSdkVersion 28
multiDexEnabled true
}
...
}
2) However, if your minSdkVersion is set to 20 or less, you should use the MultiDex compatibility library, as follows:
2.1) Modify the module-level build.gradle
file to enable MultiDex and add the MultiDex library as dependency, as shown below
android {
defaultConfig {
...
minSdkVersion 15
targetSdkVersion 28
multiDexEnabled true
}
...
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
2.2) According to the Application
class or not, do one of the following actions:
2.2.1) If you do not cancel the Application
class, modify your manifest file to set android: name
in the <application>
tag as shown below:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:name="android.support.multidex.MultiDexApplication" >
...
</application>
</manifest>
2.2.2) If you cancel the Application
class, you must change it to extend MultiDexApplication
(if possible) as shown below:
public class MyApplication extends MultiDexApplication { ... }
2.2.3) Also, if you override the Application
class and can not change the base class, alternatively you can override the attachBaseContext ()
method and invoke MultiDex.install (this)
to enable MultiDex:
public class MyApplication extends SomeOtherApplication {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
If the different dependencies have a same jar also cause this build error.
For example:
compile('com.a.b:library1');
compile('com.c.d:library2');
If "library1" and "library2" has a same jar named xxx.jar
, this will make such an error.
Besides describeBy
, the doBy
package is an another option. It provides much of the functionality of SAS PROC SUMMARY. Details:
http://www.statmethods.net/stats/descriptives.html
As I can't use Macros in my Visual Studio 2013 I found a Visual Studio Plugin (I use it in 2012 and 2013). Duplicate Selection duplicates selections and whole Lines - they only need to be partial selected. The standard shortcut is ALT + D.
To create a user with sudo privileges is to put the user into /etc/sudoers
, or make the user a member of a group specified in /etc/sudoers
. And to make it password-less is to additionally specify NOPASSWD
in /etc/sudoers
.
Example of /etc/sudoers
:
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
## Allows people in group wheel to run all commands
%wheel ALL=(ALL) ALL
## Same thing without a password
%wheel ALL=(ALL) NOPASSWD: ALL
And instead of fiddling with /etc/sudoers
file, we can create a new file in /etc/sudoers.d/
directory since this directory is included by /etc/sudoers
by default, which avoids the possibility of breaking existing sudoers file, and also eliminates the dependency on the content inside of /etc/sudoers
.
To achieve above in Ansible, refer to the following:
- name: sudo without password for wheel group
copy:
content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
dest: /etc/sudoers.d/wheel_nopasswd
mode: 0440
You may replace %wheel
with other group names like %sudoers
or other user names like deployer
.
By using (
,)
, you are capturing the group, if you simply remove them you will not have this problem.
>>> str1 = "a b c d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']
However there is no need for regex, str.split
without any delimiter specified will split this by whitespace for you. This would be the best way in this case.
>>> str1.split()
['a', 'b', 'c', 'd']
If you really wanted regex you can use this ('\s'
represents whitespace and it's clearer):
>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']
or you can find all non-whitespace characters
>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']
https://www.electronjs.org/apps/asarui
UI for Asar, Extract All, or drag extract file/directory
I would prefer to do this by return. Put the looping part in private function and return when you want to break the loop.
You can use the SpringBoot plugin:
plugins {
id "org.springframework.boot" version "2.2.2.RELEASE"
}
Create the jar
gradle assemble
And then run it
java -jar build/libs/*.jar
Note: your project does NOT need to be a SpringBoot project to use this plugin.
You need to remove the scanner closing lines: scan.close();
It happened to me before and that was the reason.
You cannot, and here is the simple answer.
Every media asset poured into the browser is identified by a mime type name. A browser then makes processing determinations upon that mime type name. If it is image/gif or image/jpeg the browser processes the asset as an image. If it is text/css or text/javascript it is processed as a code asset unless the asset is addressed independent of HTML. PDF is identified as application/pdf. When browsers see application/pdf they immediately switch processing to a plugin software capable of processing that media type. If you attempt to push media of type application/pdf into a div the browser will likely throw an error to the user. Typically files of type application/pdf are linked to directly so that the processing software an intercept the request and process the media independent of the browser.
Just found out a great plugin for this:
http://flexslider.woothemes.com/
Regards
If you want that warm and fuzzy feeling just go with with.
For python 3.6 I ran these two programs under a fresh start of IDLE, giving runtimes of:
0.002000093460083008 Test A
0.0020003318786621094 Test B: with guaranteed close
So not much of a difference.
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: Test A for reading a text file line-by-line into a list
#--------*---------*---------*---------*---------*---------*---------*---------*
import sys
import time
# # MAINLINE
if __name__ == '__main__':
print("OK, starting program...")
inTextFile = '/Users/Mike/Desktop/garbage.txt'
# # Test: A: no 'with;
c=[]
start_time = time.time()
c = open(inTextFile).read().splitlines()
print("--- %s seconds ---" % (time.time() - start_time))
print("OK, program execution has ended.")
sys.exit() # END MAINLINE
OUTPUT:
OK, starting program...
--- 0.002000093460083008 seconds ---
OK, program execution has ended.
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: Test B for reading a text file line-by-line into a list
#--------*---------*---------*---------*---------*---------*---------*---------*
import sys
import time
# # MAINLINE
if __name__ == '__main__':
print("OK, starting program...")
inTextFile = '/Users/Mike/Desktop/garbage.txt'
# # Test: B: using 'with'
c=[]
start_time = time.time()
with open(inTextFile) as D: c = D.read().splitlines()
print("--- %s seconds ---" % (time.time() - start_time))
print("OK, program execution has ended.")
sys.exit() # END MAINLINE
OUTPUT:
OK, starting program...
--- 0.0020003318786621094 seconds ---
OK, program execution has ended.
Placing @EdChum's very nice answer into a function count_unique_index
.
The unique method only works on pandas series, not on data frames.
The function below reproduces the behavior of the unique function in R:
unique returns a vector, data frame or array like x but with duplicate elements/rows removed.
And adds a count of the occurrences as requested by the OP.
df1 = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],
'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})
def count_unique_index(df, by):
return df.groupby(by).size().reset_index().rename(columns={0:'count'})
count_unique_index(df1, ['A','B'])
A B count
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
Jaqen H'ghar is spot-on. A third way is to:
Code that runs on application startup:
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition {
Path = "~/Scripts/jquery.validate.unobtrusive.min.js",
DebugPath = "~/Scripts/jquery.validate.unobtrusive.min.js"
});
I got this error message too.
and what makes me think it is useful to give an answer here is that the answer from @Rafal Rawicki is a good solution in some cases but not for all circumstances. example that i met:
1.run "git log" we can get the HEAD commit change-id
2.we also can get a 'HEAD' commit change-id on Gerrit website.
3.they are different ,which makes us can not push successfully and get the "missing change-id error"
solution:
0.'git add .'
1.save your HEAD commit change-id got from 'git log',it will be used later.
2.copy the HEAD commit change-id from Gerrit website.
3.'git reset HEAD'
4.'git commit --amend' and copy the change-id from **Gerrit website** to the commit message in the last paragraph(replace previous change-id)
5.'git push *' you can push successfully now but can not find the HEAD commit from **git log** on Gerrit website too
6.'git reset HEAD'
7.'git commit --amend' and copy the change-id from **git log**(we saved in step 1) to the commit message in the last paragraph(replace previous change-id)
8.'git push *' you can find the HEAD commit from **git log** on Gerrit website,they have the same change-id
9.done
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
After doing some research and testing, the only correct implementation is:
setTimeout(yourFunctionReference, 4000, param1, param2, paramN);
setTimeout will pass all extra parameters to your function so they can be processed there.
The anonymous function can work for very basic stuff, but within instance of a object where you have to use "this", there is no way to make it work. Any anonymous function will change "this" to point to window, so you will lose your object reference.
Just coerce the StatusCode
to int
.
var statusNumber;
try {
response = (HttpWebResponse)request.GetResponse();
// This will have statii from 200 to 30x
statusNumber = (int)response.StatusCode;
}
catch (WebException we) {
// Statii 400 to 50x will be here
statusNumber = (int)we.Response.StatusCode;
}
Use xsd:include to bring in an XSD from the same or no namespace.
Use xsd:import to bring in an XSD from a different namespace.
With Django version 1.3, the class based approach is:
from django.conf.urls.defaults import patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^some-url/$', RedirectView.as_view(url='/redirect-url/'), name='some_redirect'),
)
This example lives in in urls.py
That will only work if register_globals
is on, and it should never be on (unless of course you are defining that variable somewhere else).
Try setting the form
's action
attribute to ?
...
<form method="post" action="?">
...
</form>
You can also set it to be blank (""
), but older WebKit versions had a bug.
Change your css as below
#element1 {float:left;margin-right:10px;}
#element2 {float:left;}
Here is the JSFiddle http://jsfiddle.net/a4aME/
The EditorFor html helper does not have overloads that take HTML attributes. In this case, you need to use something more specific like TextBoxFor:
<div class="editor-field">
@Html.TextBoxFor(model => model.userName, new
{ disabled = "disabled", @readonly = "readonly" })
</div>
You can still use EditorFor, but you will need to have a TextBoxFor in a custom EditorTemplate:
public class MyModel
{
[UIHint("userName")]
public string userName { ;get; set; }
}
Then, in your Views/Shared/EditorTemplates folder, create a file userName.cshtml. In that file, put this:
@model string
@Html.TextBoxFor(m => m, new { disabled = "disabled", @readonly = "readonly" })
And just because it's always more fun to do stuff in one line...
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
NOTE: This DOES NOT prevent a user from Copy / Paste into this textbox. It's not a fail safe way to sanitize your data.
sed '/^$/d'
should be fine, are you expecting to modify the file in place? If so you should use the -i
flag.
Maybe those lines are not empty, so if that's the case, look at this question Remove empty lines from txtfiles, remove spaces from start and end of line I believe that's what you're trying to achieve.
Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.
You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:
<body oncopy="return false" oncut="return false" onpaste="return false">
How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers
A more advanced aproach:
How to detect Ctrl+V, Ctrl+C using JavaScript?
Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.
For Mobile Safari There is a Browser fix. you need to add -webkit-box for iOS devices.
Ex.
display: flex;
display: -webkit-box;
flex-direction: column;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
align-items: stretch;
if you're using align-items: stretch;
property for parent element, remove the height : 100%
from the child element.
Just pass appropriate Comparator
to the constructor:
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
The only difference between offer
and add
is the interface they belong to. offer
belongs to Queue<E>
, whereas add
is originally seen in Collection<E>
interface. Apart from that both methods do exactly the same thing - insert the specified element into priority queue.
You can check this link: http://jqueryui.com/dialog/
This code should work fine
$("#dialog").dialog();
If you do this a lot, NumPy is the way to go.
If for some reason you can't use NumPy:
>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]
In C++11 you can do now:
class A {
private:
static constexpr const char* STRING = "some useful string constant";
};
This is for the searchers,
The best I did is,
$('#myDiv *').attr("disabled", true);
$('#myDiv *').fadeTo('slow', .6);
In addition to the popular answer above I would like to add a few notes for Windows-systems. The command
git filter-branch --tree-filter 'rm -rf node_modules' --prune-empty HEAD
works perfectly without any modification! Therefore, you must not use Remove-Item
, del
or anything else instead of rm -rf
.
If you need to specify a path to a file or directory use slashes like ./path/to/node_modules
You can affect an anonymous object casted in your class type. Bonus: In visual studio, you benefit of intellisense this way :)
var anInstance: AClass = <AClass> {
Property1: "Value",
Property2: "Value",
PropertyBoolean: true,
PropertyNumber: 1
};
Edit:
WARNING If the class has methods, the instance of your class will not get them. If AClass has a constructor, it will not be executed. If you use instanceof AClass, you will get false.
In conclusion, you should used interface and not class. The most common use is for the domain model declared as Plain Old Objects. Indeed, for domain model you should better use interface instead of class. Interfaces are use at compilation time for type checking and unlike classes, interfaces are completely removed during compilation.
interface IModel {
Property1: string;
Property2: string;
PropertyBoolean: boolean;
PropertyNumber: number;
}
var anObject: IModel = {
Property1: "Value",
Property2: "Value",
PropertyBoolean: true,
PropertyNumber: 1
};
C# code:
var jsonSerializerSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var jsonString = JsonConvert.SerializeObject(object2Serialize, jsonSerializerSettings);
var filePath = @"E:\json.json";
File.WriteAllText(filePath, jsonString);
I resizeed the image in such a way and it's working very well
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import os, sys
from PIL import Image
def imageResize(image):
outputIoStream = BytesIO()
imageTemproaryResized = imageTemproary.resize( (1920,1080), Image.ANTIALIAS)
imageTemproaryResized.save(outputIoStream , format='PNG', quality='10')
outputIoStream.seek(0)
uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)
## For upload local folder
fs = FileSystemStorage()
filename = fs.save(uploadedImage.name, uploadedImage)
Based on answers suggested by many authors, I created a JsPref test scenario. https://jsperf.com/array2object82364
Below are the screenshots of performance. It is a little shocking to me to see, chrome result is in contrast to firefox and edge, even after running it several times.
Object getResult = obj.get("dps");
if (getResult != null && getResult instanceof java.util.Map && (java.util.Map)getResult.isEmpty()) {
handleEmptyDps();
}
else {
handleResult(getResult);
}
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
Θ-notation (theta notation) is called tight-bound because it's more precise than O-notation and Ω-notation (omega notation).
If I were lazy, I could say that binary search on a sorted array is O(n2), O(n3), and O(2n), and I would be technically correct in every case. That's because O-notation only specifies an upper bound, and binary search is bounded on the high side by all of those functions, just not very closely. These lazy estimates would be useless.
Θ-notation solves this problem by combining O-notation and Ω-notation. If I say that binary search is Θ(log n), that gives you more precise information. It tells you that the algorithm is bounded on both sides by the given function, so it will never be significantly faster or slower than stated.
You could use a combination of the UNIX_TIMESTAMP() function to do that.
SELECT ... FROM ... WHERE UNIX_TIMESTAMP() - UNIX_TIMESTAMP(thefield) < 259200
basically i use this in one of our apps: we want to overlay a playicon over a frame of a video:
Image playbutton;
try
{
playbutton = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
return;
}
Image frame;
try
{
frame = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
return;
}
using (frame)
{
using (var bitmap = new Bitmap(width, height))
{
using (var canvas = Graphics.FromImage(bitmap))
{
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.DrawImage(frame,
new Rectangle(0,
0,
width,
height),
new Rectangle(0,
0,
frame.Width,
frame.Height),
GraphicsUnit.Pixel);
canvas.DrawImage(playbutton,
(bitmap.Width / 2) - (playbutton.Width / 2),
(bitmap.Height / 2) - (playbutton.Height / 2));
canvas.Save();
}
try
{
bitmap.Save(/*somekindofpath*/,
System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex) { }
}
}
Try ROW_NUMBER()
http://msdn.microsoft.com/en-us/library/ms186734.aspx
Example:
SELECT
col1,
col2,
ROW_NUMBER() OVER (ORDER BY col1) AS rownum
FROM tbl
Sorry for dredging up an old post, but it has a lot of views. I faced a similar problem this week and came up with this pattern:
declare @example table ( sampletext varchar( 50 ) );
insert @example values
( 'The quick brown fox jumped over the lazy dog.' ),
( 'Ask not what your country can do for you.' ),
( 'Cupcakes are the new hotness.' );
declare @filter table ( searchtext varchar( 50 ) );
insert @filter values
( 'lazy' ),
( 'hotness' ),
( 'cupcakes' );
-- Expect to get rows 1 and 3, but no duplication from Cupcakes and Hotness
select *
from @example e
where exists ( select * from @filter f where e.sampletext like '%' + searchtext + '%' )
Exists() works a little better than join, IMO, because it just tests each record in the set, but doesn't cause duplication if there are multiple matches.
I'm not sure how portable it is across operating systems, but you might check if your system contains the 'run-one' command, i.e. "man run-one". Specifically, this set of commands includes 'run-one-constantly', which seems to be exactly what is needed.
From man page:
run-one-constantly COMMAND [ARGS]
Note: obviously this could be called from within your script, but also it removes the need for having a script at all.
let groupbyKeys = function(arr, ...keys) {
let keysFieldName = keys.join();
return arr.map(ele => {
let keysField = {};
keysField[keysFieldName] = keys.reduce((keyValue, key) => {
return keyValue + ele[key]
}, "");
return Object.assign({}, ele, keysField);
}).reduce((groups, ele) => {
(groups[ele[keysFieldName]] = groups[ele[keysFieldName]] || [])
.push([ele].map(e => {
if (keys.length > 1) {
delete e[keysFieldName];
}
return e;
})[0]);
return groups;
}, {});
};
console.log(groupbyKeys(array, 'Phase'));
console.log(groupbyKeys(array, 'Phase', 'Step'));
console.log(groupbyKeys(array, 'Phase', 'Step', 'Task'));
If you want to make address directly, the worksheet must exist.
Turning off automatic recalculation want help you :)
But... you can get value indirectly...
.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"
At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.
But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.
use g++
instead of gcc
.
Moved from the closed topic
del /s d:\test\archive*.txt
This should get you all of your text files
Alternatively,
I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.
Please test this on your system before using it though.
@echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION
REM ---------------------------
REM *** EDIT VARIABLES BELOW ***
REM ---------------------------
set targetFolder=
REM targetFolder is the location you want to delete from
REM ---------------------------
REM *** DO NOT EDIT BELOW ***
REM ---------------------------
IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
set "Subfolders[!Index!]=%%D"
set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!
:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in:
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start
:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end
:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end
:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit
REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)
If you change the
set targetFolder=
to the folder you want you won't get prompted for the folder. *Remember when putting the base path in, the format does not include a '\' on the end. e.g. d:\test c:\temp
Hope this helps
Looks like you typed brackets instead of parenthesis by mistake.
Using python-dateutil:
In [1]: import dateutil.parser as dparser
In [18]: dparser.parse("monkey 2010-07-10 love banana",fuzzy=True)
Out[18]: datetime.datetime(2010, 7, 10, 0, 0)
Invalid dates raise a ValueError
:
In [19]: dparser.parse("monkey 2010-07-32 love banana",fuzzy=True)
# ValueError: day is out of range for month
It can recognize dates in many formats:
In [20]: dparser.parse("monkey 20/01/1980 love banana",fuzzy=True)
Out[20]: datetime.datetime(1980, 1, 20, 0, 0)
Note that it makes a guess if the date is ambiguous:
In [23]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True)
Out[23]: datetime.datetime(1980, 10, 1, 0, 0)
But the way it parses ambiguous dates is customizable:
In [21]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True, dayfirst=True)
Out[21]: datetime.datetime(1980, 1, 10, 0, 0)
A database is the computerized logical representation of a conceptual (or business) model, consisting of a set of informal business rules. These rules are the user-understood meaning of the data. Because computers comprehend only formal representations, business rules cannot be represented directly in a database. They must be mapped to a formal representation, a logical model, which consists of a set of integrity constraints. These constraints — the database schema — are the logical representation in the database of the business rules and, therefore, are the DBMS-understood meaning of the data. It follows that if the DBMS is unaware of and/or does not enforce the full set of constraints representing the business rules, it has an incomplete understanding of what the data means and, therefore, cannot guarantee (a) its integrity by preventing corruption, (b) the integrity of inferences it makes from it (that is, query results) — this is another way of saying that the DBMS is, at best, incomplete.
Note: The DBMS-“understood” meaning — integrity constraints — is not identical to the user-understood meaning — business rules — but, the loss of some meaning notwithstanding, we gain the ability to mechanize logical inferences from the data.
"An Old Class of Errors" by Fabian Pascal
I updated my requirements.txt
to have
psycopg2==2.7.4 --no-binary=psycopg2
So that it build binaries on source
I didn't have luck with some of the above,
This was the only one that actually worked for me
ul:not(:first-of-type) {}
This worked for me when I was trying to have the first button displayed on the page not be effected by a margin-left option.
this was the option I tried first but it didn't work
ul:not(:first-child)
First of all my Search query value is from a user's input. I have tried all the answers on this one and all the results Google have given me, 90% of the answers says put '%''%' and the other 10% says a more complicated answers.
For some reason all of those did not work for me.
How ever I remembered that in MySQL (phpmyadmin) there is this built in search function so I tried it just to see how MySQL handles a search with an apostrophe, turns out MySQL just escaping apostrophe with a backslash LIKE '%\'%'
so why just I replace apostrophe with a \'
in every user's query.
This is what I come up with:
if(!empty($user_search)) {
$r_user_search = str_ireplace("'","\'","$user_search");
$find_it = "SELECT * FROM table WHERE column LIKE '%$r_user_search%'";
$results = $pdo->prepare($find_it);
$results->execute();
This solves my problem. Also please correct me if this is still has security issues.
select * into newtable from oldtable
also this might be of use to know the logical difference between join, exists and in http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx
Generally, using Promise.all()
runs requests "async" in parallel. Using await
can run in parallel OR be "sync" blocking.
test1 and test2 functions below show how await
can run async or sync.
test3 shows Promise.all()
that is async.
jsfiddle with timed results - open browser console to see test results
Sync behavior. Does NOT run in parallel, takes ~1800ms:
const test1 = async () => {
const delay1 = await Promise.delay(600); //runs 1st
const delay2 = await Promise.delay(600); //waits 600 for delay1 to run
const delay3 = await Promise.delay(600); //waits 600 more for delay2 to run
};
Async behavior. Runs in paralel, takes ~600ms:
const test2 = async () => {
const delay1 = Promise.delay(600);
const delay2 = Promise.delay(600);
const delay3 = Promise.delay(600);
const data1 = await delay1;
const data2 = await delay2;
const data3 = await delay3; //runs all delays simultaneously
}
Async behavior. Runs in parallel, takes ~600ms:
const test3 = async () => {
await Promise.all([
Promise.delay(600),
Promise.delay(600),
Promise.delay(600)]); //runs all delays simultaneously
};
TLDR; If you are using Promise.all()
it will also "fast-fail" - stop running at the time of the first failure of any of the included functions.
I am not sure if you have an old version of IntelliJ IDEA, but if I go to menu File ? Settings... ? Inspections ? Serialization issues ? Serializable class without 'serialVersionUID'` enabled, the class you provide give me warnings.
If I try the first class I see:
BTW: It didn't show me a warning until I added { }
to the end of each class to fix the compile error.
The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.
public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
T returnObject = default(T);
if (string.IsNullOrEmpty(XmlFilename)) return default(T);
try
{
StreamReader xmlStream = new StreamReader(XmlFilename);
XmlSerializer serializer = new XmlSerializer(typeof(T));
returnObject = (T)serializer.Deserialize(xmlStream);
}
catch (Exception ex)
{
ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
}
return returnObject;
}
Then you'd call it like this:
MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);
Try using delegate instead of live as here:
$('#link-wrapper').delegate('a', 'click', function() {
// do something ..
}
@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg')
before importing matplotlib.pyplot
, and then continue as normal.
E.g.
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')
You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.
Alternately, you can just set the backend parameter in your .matplotlibrc
file to automatically have matplotlib.pyplot
use the given renderer.
To improve slightly over Alex Martelli's response, the following will not only cleanup extra slashes but also preserve trailing (ending) slashes, which can sometimes be useful :
>>> items = ["http://www.website.com", "/api", "v2/"]
>>> url = "/".join([(u.strip("/") if index + 1 < len(items) else u.lstrip("/")) for index, u in enumerate(items)])
>>> print(url)
http://www.website.com/api/v2/
It's not as easy to read though, and won't cleanup multiple extra trailing slashes.
or programatically
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
I had the similar issue, 0.0% coverage & no unit tests count on Sonar dashboard with SonarQube 6.7.2: Maven : 3.5.2, Java : 1.8, Jacoco : Worked with 7.0/7.9/8.0, OS : Windows
After a lot of struggle finding for correct solution on maven multi-module project,not like single module project here we need to say to pick jacoco reports from individual modules & merge to one report,So resolved issue with this configuration as my parent pom looks like:
<properties>
<!--Sonar -->
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.4.0.905</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<configuration>
<destFile>${sonar.jacoco.reportPath}</destFile>
<append>true</append>
</configuration>
<executions>
<execution>
<id>agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
I've tried few other options like jacoco-aggregate & even creating a sub-module by including that in parent pom but nothing really worked & this is simple. I see in logs <sonar.jacoco.reportPath>
is deprecated,but still works as is and seems like auto replaced on execution or can be manually updated to <sonar.jacoco.reportPaths>
or latest. Once after doing setup in cmd start with mvn clean install then mvn org.jacoco:jacoco-maven-plugin:prepare-agent install (Check on project's target folder whether jacoco.exec is created) & then do mvn sonar:sonar , this is what I've tried please let me know if some other best possible solution available.Hope this helps!! If not please post your question..
Our variable:
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
To store:
map.put("mango", new ArrayList<Integer>(Arrays.asList(0, 4, 8, 9, 12)));
To add numbers one and one, you can do something like this:
String key = "mango";
int number = 42;
if (map.get(key) == null) {
map.put(key, new ArrayList<Integer>());
}
map.get(key).add(number);
In Java 8 you can use putIfAbsent
to add the list if it did not exist already:
map.putIfAbsent(key, new ArrayList<Integer>());
map.get(key).add(number);
Use the map.entrySet()
method to iterate on:
for (Entry<String, List<Integer>> ee : map.entrySet()) {
String key = ee.getKey();
List<Integer> values = ee.getValue();
// TODO: Do something.
}
The comparison needs to be evaluated fully inside EL ${ ... }
, not outside.
<c:if test="${values.type eq 'object'}">
As to the docs, those ${}
things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.
<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass()
and then Class#getSimpleName()
instead of adding a custom getter.
<c:forEach items="${list}" var="value">
<c:if test="${value['class'].simpleName eq 'Object'}">
<!-- code here -->
</c:if>
</c:forEeach>
I know you are not after array_unique()
. However, you will not find a magical obvious function nor will writing one be faster than making use of the native functions.
I propose:
function array_has_dupes($array) {
// streamline per @Felix
return count($array) !== count(array_unique($array));
}
Adjust the second parameter of array_unique()
to meet your comparison needs.
On Windows with Android Studio 1.5.1 : File --> Settings --> Editor --> General --> Auto Import
The AtomicBoolean
class gives you a boolean value that you can update atomically. Use it when you have multiple threads accessing a boolean variable.
The java.util.concurrent.atomic package overview gives you a good high-level description of what the classes in this package do and when to use them. I'd also recommend the book Java Concurrency in Practice by Brian Goetz.
This is a base service class (ServiceBase subclass) that can be subclassed to build a windows service that can be easily installed from the command line, without installutil.exe. This solution is derived from How to make a .NET Windows Service start right after the installation?, adding some code to get the service Type using the calling StackFrame
public abstract class InstallableServiceBase:ServiceBase
{
/// <summary>
/// returns Type of the calling service (subclass of InstallableServiceBase)
/// </summary>
/// <returns></returns>
protected static Type getMyType()
{
Type t = typeof(InstallableServiceBase);
MethodBase ret = MethodBase.GetCurrentMethod();
Type retType = null;
try
{
StackFrame[] frames = new StackTrace().GetFrames();
foreach (StackFrame x in frames)
{
ret = x.GetMethod();
Type t1 = ret.DeclaringType;
if (t1 != null && !t1.Equals(t) && !t1.IsSubclassOf(t))
{
break;
}
retType = t1;
}
}
catch
{
}
return retType;
}
/// <summary>
/// returns AssemblyInstaller for the calling service (subclass of InstallableServiceBase)
/// </summary>
/// <returns></returns>
protected static AssemblyInstaller GetInstaller()
{
Type t = getMyType();
AssemblyInstaller installer = new AssemblyInstaller(
t.Assembly, null);
installer.UseNewContext = true;
return installer;
}
private bool IsInstalled()
{
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
try
{
ServiceControllerStatus status = controller.Status;
}
catch
{
return false;
}
return true;
}
}
private bool IsRunning()
{
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
if (!this.IsInstalled()) return false;
return (controller.Status == ServiceControllerStatus.Running);
}
}
/// <summary>
/// protected method to be called by a public method within the real service
/// ie: in the real service
/// new internal void InstallService()
/// {
/// base.InstallService();
/// }
/// </summary>
protected void InstallService()
{
if (this.IsInstalled()) return;
try
{
using (AssemblyInstaller installer = GetInstaller())
{
IDictionary state = new Hashtable();
try
{
installer.Install(state);
installer.Commit(state);
}
catch
{
try
{
installer.Rollback(state);
}
catch { }
throw;
}
}
}
catch
{
throw;
}
}
/// <summary>
/// protected method to be called by a public method within the real service
/// ie: in the real service
/// new internal void UninstallService()
/// {
/// base.UninstallService();
/// }
/// </summary>
protected void UninstallService()
{
if (!this.IsInstalled()) return;
if (this.IsRunning()) {
this.StopService();
}
try
{
using (AssemblyInstaller installer = GetInstaller())
{
IDictionary state = new Hashtable();
try
{
installer.Uninstall(state);
}
catch
{
throw;
}
}
}
catch
{
throw;
}
}
private void StartService()
{
if (!this.IsInstalled()) return;
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
try
{
if (controller.Status != ServiceControllerStatus.Running)
{
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running,
TimeSpan.FromSeconds(10));
}
}
catch
{
throw;
}
}
}
private void StopService()
{
if (!this.IsInstalled()) return;
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
try
{
if (controller.Status != ServiceControllerStatus.Stopped)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped,
TimeSpan.FromSeconds(10));
}
}
catch
{
throw;
}
}
}
}
All you have to do is to implement two public/internal methods in your real service:
new internal void InstallService()
{
base.InstallService();
}
new internal void UninstallService()
{
base.UninstallService();
}
and then call them when you want to install the service:
static void Main(string[] args)
{
if (Environment.UserInteractive)
{
MyService s1 = new MyService();
if (args.Length == 1)
{
switch (args[0])
{
case "-install":
s1.InstallService();
break;
case "-uninstall":
s1.UninstallService();
break;
default:
throw new NotImplementedException();
}
}
}
else {
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(MyService);
}
}
I have published a header file to perform the switch on the strings in C. It contains a set of macro that hide the call to the strcmp() (or similar) in order to mimic a switch-like behaviour. I have tested it only with GCC in Linux, but I'm quite sure that it can be adapted to support other environment.
EDIT: added the code here, as requested
This is the header file you should include:
#ifndef __SWITCHS_H__
#define __SWITCHS_H__
#include <string.h>
#include <regex.h>
#include <stdbool.h>
/** Begin a switch for the string x */
#define switchs(x) \
{ char *__sw = (x); bool __done = false; bool __cont = false; \
regex_t __regex; regcomp(&__regex, ".*", 0); do {
/** Check if the string matches the cases argument (case sensitive) */
#define cases(x) } if ( __cont || !strcmp ( __sw, x ) ) \
{ __done = true; __cont = true;
/** Check if the string matches the icases argument (case insensitive) */
#define icases(x) } if ( __cont || !strcasecmp ( __sw, x ) ) { \
__done = true; __cont = true;
/** Check if the string matches the specified regular expression using regcomp(3) */
#define cases_re(x,flags) } regfree ( &__regex ); if ( __cont || ( \
0 == regcomp ( &__regex, x, flags ) && \
0 == regexec ( &__regex, __sw, 0, NULL, 0 ) ) ) { \
__done = true; __cont = true;
/** Default behaviour */
#define defaults } if ( !__done || __cont ) {
/** Close the switchs */
#define switchs_end } while ( 0 ); regfree(&__regex); }
#endif // __SWITCHS_H__
And this is how you use it:
switchs(argv[1]) {
cases("foo")
cases("bar")
printf("foo or bar (case sensitive)\n");
break;
icases("pi")
printf("pi or Pi or pI or PI (case insensitive)\n");
break;
cases_re("^D.*",0)
printf("Something that start with D (case sensitive)\n");
break;
cases_re("^E.*",REG_ICASE)
printf("Something that start with E (case insensitive)\n");
break;
cases("1")
printf("1\n");
// break omitted on purpose
cases("2")
printf("2 (or 1)\n");
break;
defaults
printf("No match\n");
break;
} switchs_end;
All the timers have the equivalent of Start() and Stop() methods, except System.Threading.Timer.
So an extension method such as...
public static void Reset(this Timer timer)
{
timer.Stop();
timer.Start();
}
...is one way to go about it.
It depends. You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.
Didn't see how this fit into the flow of the main answer but it stumped me for a while so I'm adding it here:
To see the source code of some base infix operators (e.g., %%
, %*%
, %in%
), use getAnywhere
, e.g.:
getAnywhere("%%")
# A single object matching ‘%%’ was found
# It was found in the following places
# package:base
# namespace:base
# with value
#
# function (e1, e2) .Primitive("%%")
The main answer covers how to then use mirrors to dig deeper.
Open "command or conda prompt" and run:
conda update conda
conda update anaconda
It's a good idea to run both command twice (one after the other) to be sure that all the basic files are updated.
This should put you back on the latest 'releases', which contains packages that are selected by the people at Continuum to work well together.
If you want the last version of each package run (this can lead to an unstable environment):
conda update --all
Hope this helps.
Sources:
Try this:
methods: {
formatPrice(value) {
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'PHP',
minimumFractionDigits: 2
});
return formatter.format(value);
},
}
Then you can just call this like:
{{ formatPrice(item.total) }}
Perhaps use information_schema:
SELECT EXISTS(
SELECT *
FROM information_schema.tables
WHERE
table_schema = 'company3' AND
table_name = 'tableincompany3schema'
);
$string_val = 'a.b';
$parts = explode('.', $string_val);
print_r($parts);
names = [];
$('input[name=text], textarea').each(
function(index){
var input = $(this);
names.push( input.attr('name') );
//input.attr('id');
}
);
it select all textboxes and textarea in your DOM, where $.each function iterates to provide name of ecah element.
[function.fopen]: failed to open stream
If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :
allow_url_fopen = off
should bee this
allow_url_fopen = On
And add this line below it:
allow_url_include = off
should bee this
allow_url_include = on
Taken from this answer.
packages.config
file. This is the first time I see ignoring a problem actually makes it go away...
Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can
I agree with Duncan ...I have tried it with mutable object but still get the same problem... I got a simple solution to this... use ListIterator instead Iterator and use set method of ListIterator
ListIterator<Integer> i = a.listIterator();
//changed the value of first element in List
Integer x =null;
if(i.hasNext()) {
x = i.next();
x = Integer.valueOf(9);
}
//set method sets the recent iterated element in ArrayList
i.set(x);
//initialized the iterator again and print all the elements
i = a.listIterator();
while(i.hasNext())
System.out.print(i.next());
But this constraints me to use this only for ArrayList only which can use ListIterator...i will have same problem with any other Collection
By having struggling so many hours on applying GitHub token finally it works as below:
$ cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)
%d%H%M
on match word '-123456-whatever'
Following is the complete code:
version: '1.0'
steps:
get_git_token:
title: Reading Github token
image: codefresh/cli
commands:
- cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)
main_clone:
title: Updating the repo
image: alpine/git:latest
commands:
- git clone https://chetabahana:[email protected]/chetabahana/compose.git
- cd compose && git remote rm origin
- git config --global user.name "chetabahana"
- git config --global user.email "[email protected]"
- git remote add origin https://chetabahana:[email protected]/chetabahana/compose.git
- sed -i "s/-[0-9]\{1,\}-\([a-zA-Z0-9_]*\)'/-`date +%d%H%M`-whatever'/g" cloudbuild.yaml
- git status && git add . && git commit -m "fresh commit" && git push -u origin master
Output...
On branch master
Changes not staged for commit:
(use "git add ..." to update what will be committed)
(use "git checkout -- ..." to discard changes in working directory)
modified: cloudbuild.yaml
no changes added to commit (use "git add" and/or "git commit -a")
[master dbab20f] fresh commit
1 file changed, 1 insertion(+), 1 deletion(-)
Enumerating objects: 5, done.
Counting objects: 20% (1/5) ... Counting objects: 100% (5/5), done.
Delta compression using up to 4 threads
Compressing objects: 33% (1/3) ... Writing objects: 100% (3/3), 283 bytes | 283.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 0% (0/2) ... (2/2), completed with 2 local objects.
To https://github.com/chetabahana/compose.git
bbb6d2f..dbab20f master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.
Reading environment variable exporting file contents.
Successfully ran freestyle step: Cloning the repo
Another way to find out where a class is loaded from (without manipulating the source) is to start the Java VM with the option: -verbose:class
If you are using 5.0x version,configuration with standard service registry is deprecated.
Instead you should bootstrap it with Metadata: In your HibernateUtil class, you should add
private static SessionFactory buildSessionFactory() {
try {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure( "hibernate.cfg.xml" )
.build();
Metadata metadata = new MetadataSources( standardRegistry )
.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder().build();
} catch(...) {
...
}
}
To change dir
foo:
$(MAKE) -C mydir
multi:
$(MAKE) -C / -C my-custom-dir ## Equivalent to /my-custom-dir
I have encountered this error code when enumerating names and calling worksheet.get_Range(name). It seems to occur when the name does NOT apply to a range, in my case it is the name of a macro.
>>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN])
>>> s[~s.isnull()]
0 1
1 2
2 3
3 4
5 5
update or even better approach as @DSM suggested in comments, using pandas.Series.dropna()
:
>>> s.dropna()
0 1
1 2
2 3
3 4
5 5
If you don't mind reading bytecode, javap should work fine. It's part of the standard JDK installation.
Usage: javap <options> <classes>...
where options include:
-c Disassemble the code
-classpath <pathlist> Specify where to find user class files
-extdirs <dirs> Override location of installed extensions
-help Print this usage message
-J<flag> Pass <flag> directly to the runtime system
-l Print line number and local variable tables
-public Show only public classes and members
-protected Show protected/public classes and members
-package Show package/protected/public classes
and members (default)
-private Show all classes and members
-s Print internal type signatures
-bootclasspath <pathlist> Override location of class files loaded
by the bootstrap class loader
-verbose Print stack size, number of locals and args for methods
If verifying, print reasons for failure
This is a very simple way of doing it with no functionality and all visual effect,
Use a grid and just simply customise it.
<Grid Background="DodgerBlue" Height="250" Width="1" VerticalAlignment="Center" Margin="5,0,5,0"/>
Just another way to do it.
Using ES6 the javascript becomes a little cleaner
handleFiles(input) {
const file = input.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const file = event.target.result;
const allLines = file.split(/\r\n|\n/);
// Reading line by line
allLines.forEach((line) => {
console.log(line);
});
};
reader.onerror = (event) => {
alert(event.target.error.name);
};
reader.readAsText(file);
}
You are not using the function in_array (http://php.net/manual/en/function.in-array.php) correctly:
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
The $needle has to have a value in the array, so you first need to extract the url from the string (with a regular expression for example). Something like this:
$url = extrctUrl('my domain name is website3.com');
//$url will be 'website3.com'
in_array($url, $owned_urls)
There is no functional or performance difference between the two. Use whichever syntax appeals to you.
It's just like the use of AS and IS when declaring a function or procedure. They are completely interchangeable.
Hi here is how i did it in one Project :
@Html.DropDownListFor(model => model.MyOption,
new List<SelectListItem> {
new SelectListItem { Value = "0" , Text = "Option A" },
new SelectListItem { Value = "1" , Text = "Option B" },
new SelectListItem { Value = "2" , Text = "Option C" }
},
new { @class="myselect"})
I hope it helps Somebody. Thanks
Instead of using ->bindParam()
you can pass the data only at the time of ->execute()
:
$data = [ ':item_name' => $_POST['item_name'], ':item_type' => $_POST['item_type'], ':item_price' => $_POST['item_price'], ':item_description' => $_POST['item_description'], ':image_location' => 'images/'.$_FILES['file']['name'], ':status' => 0, ':id' => 0, ]; $stmt->execute($data);
In this way you would know exactly what values are going to be sent.
Two ways:
Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.
Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.
Arrays.asList(array)
Arrays
uses new ArrayList(array)
. But this is not the java.util.ArrayList
. It's very similar though. Note that this constructor takes the array and places it as the backing array of the list. So it is O(1)
.
In case you already have the list created, Collections.addAll(list, array)
, but that's less efficient.
Update: Thus your Collections.addAll(list, array)
becomes a good option. A wrapper of it is guava's Lists.newArrayList(array)
.
You can validate group checkbox and radio button without extra js code, see below example.
Your JS should be look like:
$("#formid").validate();
You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]
<fieldset class="col-md-12">
<legend>Days</legend>
<div class="form-row">
<div class="col-12 col-md-12 form-group">
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="2">Tuesday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="3">Wednesday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="4">Thursday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="5">Friday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="6">Saturday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="7">Sunday
</label>
<label for="daysgroup[]" class="error">Your error message will be display here.</label>
</div>
</div>
</fieldset>
You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.
eg. group radio button:
<fieldset class="col-md-12">
<legend>Gender</legend>
<div class="form-row">
<div class="col-12 col-md-12 form-group">
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
</label>
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="w">woman
</label>
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="o">other
</label>
<label for="gendergroup[]" class="error">Your error message will be display here.</label>
</div>
</div>
</fieldset>
You can check working example here.
I had the same problem, but my id was present. So I tried adding "window.onload = init;" Then I wrapped my original JS code with an init function (call it what you want). This worked, so at least in my case, I was adding an event listener before my document loaded. This could be what you are experiencing as well.
function dayOfWeek($date){
return DateTime::createFromFormat('Y-m-d', $date)->format('N');
}
Usage examples:
echo dayOfWeek(2016-12-22);
// "4"
echo dayOfWeek(date('Y-m-d'));
// "4"
In Bootstrap, the .btn
class has a white-space: nowrap;
property, making it so that the button text won't wrap. So, after setting that to normal
, and giving the button a width
, the text should wrap to the next line if the text would exceed the set width
.
#new-board-btn {
white-space: normal;
}
I've tested two ways in Firefox, Chrome, IE9 and Safari.
(1). $(document.activeElement)
works as expected in Firefox, Chrome and Safari.
(2). $(':focus')
works as expected in Firefox and Safari.
I moved into the mouse to input 'name' and pressed Enter on keyboard, then I tried to get the focused element.
(1). $(document.activeElement)
returns the input:text:name as expected in Firefox, Chrome and Safari, but it returns input:submit:addPassword in IE9
(2). $(':focus')
returns input:text:name as expected in Firefox and Safari, but nothing in IE
<form action="">
<div id="block-1" class="border">
<h4>block-1</h4>
<input type="text" value="enter name here" name="name"/>
<input type="button" value="Add name" name="addName"/>
</div>
<div id="block-2" class="border">
<h4>block-2</h4>
<input type="text" value="enter password here" name="password"/>
<input type="submit" value="Add password" name="addPassword"/>
</div>
</form>
myfun <- function(x, arg1) {
# doing something here with x and arg1
}
x
is a vector or a list and myfun
in lapply(x, myfun)
is called for each element of x
separately.
Option 1
If you'd like to use whole arg1
in each myfun
call (myfun(x[1], arg1)
, myfun(x[2], arg1)
etc.), use lapply(x, myfun, arg1)
(as stated above).
Option 2
If you'd however like to call myfun
to each element of arg1
separately alongside elements of x
(myfun(x[1], arg1[1])
, myfun(x[2], arg1[2])
etc.), it's not possible to use lapply
. Instead, use mapply(myfun, x, arg1)
(as stated above) or apply
:
apply(cbind(x,arg1), 1, myfun)
or
apply(rbind(x,arg1), 2, myfun).
TRY THIS
IF EXISTS
(
SELECT name FROM master.dbo.sysdatabases
WHERE name = N'New_Database'
)
BEGIN
SELECT 'Database Name already Exist' AS Message
END
ELSE
BEGIN
CREATE DATABASE [New_Database]
SELECT 'New Database is Created'
END
To expand on Bartho Bernsmann's answer, I should like to add that one can have a universal, future-proof implementation at the expense of a little reflection:
static void AllowAllSecurityPrototols()
{ int i, n;
Array types;
SecurityProtocolType combined;
types = Enum.GetValues( typeof( SecurityProtocolType ) );
combined = ( SecurityProtocolType )types.GetValue( 0 );
n = types.Length;
for( i = 1; i < n; i += 1 )
{ combined |= ( SecurityProtocolType )types.GetValue( i ); }
ServicePointManager.SecurityProtocol = combined;
}
I invoke this method in the static constructor of the class that accesses the internet.
From RFC 4918 (and also documented at http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml):
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Your dialog should not be a "long-lived object that needs a context". The documentation is confusing. Basically if you do something like:
static Dialog sDialog;
(note the static)
Then in an activity somewhere you did
sDialog = new Dialog(this);
You would likely be leaking the original activity during a rotation or similar that would destroy the activity. (Unless you clean up in onDestroy, but in that case you probably wouldn't make the Dialog object static)
For some data structures it would make sense to make them static and based off the application's context, but generally not for UI related things, like dialogs. So something like this:
Dialog mDialog;
...
mDialog = new Dialog(this);
Is fine and shouldn't leak the activity as mDialog would be freed with the activity since it's not static.
Okay I just detached and reattach to the screen session and I am back to normal screen I wanted
This might help http://docs.pytest.org/en/latest/xunit_setup.html
In my test suite, I group my test cases into classes. For the setup and teardown I need for all the test cases in that class, I use the setup_class(cls)
and teardown_class(cls)
classmethods.
And for the setup and teardown I need for each of the test case, I use the setup_method(method)
and teardown_method(methods)
Example:
lh = <got log handler from logger module>
class TestClass:
@classmethod
def setup_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
@classmethod
def teardown_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
def setup_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def teardown_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def test_tc1(self):
<tc_content>
assert
def test_tc2(self):
<tc_content>
assert
Now when I run my tests, when the TestClass execution is starting, it logs the details for when it is beginning execution, when it is ending execution and same for the methods..
You can add up other setup and teardown steps you might have in the respective locations.
Hope it helps!
Just to add to this answer by Kamilk : https://www.stackoverflow.com/a/13905589
Depends a lot on how large dataset you are working on. Small data sets do work on effectively on offset pagination but large realtime datasets do require cursor pagination.
Found a wonderful article on how Slack evolved its api's pagination as there datasets increased explaining the positives and negatives at every stage : https://slack.engineering/evolving-api-pagination-at-slack-1c1f644f8e12
In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b
contains of an independent subexpression a / b
, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double
. a / b
is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works.
One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading
void foo(int);
void foo(double);
void (*p)(double) = &foo; // automatically selects `foo(fouble)`
This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side.
With python3, iterate on dic.keys() will raise the dictionary size error. You can use this alternative way:
Tested with python3, it works fine and the Error "dictionary changed size during iteration" is not raised:
my_dic = { 1:10, 2:20, 3:30 }
# Is important here to cast because ".keys()" method returns a dict_keys object.
key_list = list( my_dic.keys() )
# Iterate on the list:
for k in key_list:
print(key_list)
print(my_dic)
del( my_dic[k] )
print( my_dic )
# {}
The best way to deal with this (if a declaration file is not available on DefinitelyTyped) is to write declarations only for the things you use rather than the entire library. This reduces the work a lot - and additionally the compiler is there to help out by complaining about missing methods.
For Java 8 and higher:
String[] test = {"1", "2", "3", "4", "5"};
int[] ints = Arrays.stream(test).mapToInt(Integer::parseInt).toArray();
Why nobody use the event
object returned by jQuery
on scroll ?
$window.on('scroll', function (event) {
console.group('Scroll');
console.info('Scroll event:', event);
console.info('Position:', this.pageYOffset);
console.info('Direction:', event.originalEvent.dir); // Here is the direction
console.groupEnd();
});
I'm using chromium
and I didn't checked on other browsers if they have the dir
property.
This is what i did to make it work. Make sure you put
webHttp automaticFormatSelectionEnabled="true" inside endpoint behaviour.
[ServiceContract]
public interface ITestService
{
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/product", ResponseFormat = WebMessageFormat.Json)]
string GetData();
}
public class TestService : ITestService
{
public string GetJsonData()
{
return "I am good...";
}
}
Inside service model
<service name="TechCity.Business.TestService">
<endpoint address="soap" binding="basicHttpBinding" name="SoapTest"
bindingName="BasicSoap" contract="TechCity.Interfaces.ITestService" />
<endpoint address="mex"
contract="IMetadataExchange" binding="mexHttpBinding"/>
<endpoint behaviorConfiguration="jsonBehavior" binding="webHttpBinding"
name="Http" contract="TechCity.Interfaces.ITestService" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8739/test" />
</baseAddresses>
</host>
</service>
EndPoint Behaviour
<endpointBehaviors>
<behavior name="jsonBehavior">
<webHttp automaticFormatSelectionEnabled="true" />
<!-- use JSON serialization -->
</behavior>
</endpointBehaviors>
The main rule here is that:
The selectors which are applicable during compilation of a component template are determined by the module that declares that component, and the transitive closure of the exports of that module's imports.
So, try to export it:
@NgModule({
declarations: [TaskCardComponent],
imports: [MdCardModule],
exports: [TaskCardComponent] <== this line
})
export class TaskModule{}
What should I export?
Export declarable classes that components in other modules should be able to reference in their templates. These are your public classes. If you don't export a class, it stays private, visible only to other component declared in this module.
The minute you create a new module, lazy or not, any new module and you declare anything into it, that new module has a clean state(as Ward Bell said in https://devchat.tv/adv-in-angular/119-aia-avoiding-common-pitfalls-in-angular2)
Angular creates transitive module for each of @NgModule
s.
This module collects directives that either imported from another module(if transitive module of imported module has exported directives) or declared in current module.
When angular compiles template that belongs to module X
it is used those directives that had been collected in X.transitiveModule.directives.
compiledTemplate = new CompiledTemplate(
false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);
https://github.com/angular/angular/blob/4.2.x/packages/compiler/src/jit/compiler.ts#L250-L251
This way according to the picture above
YComponent
can't use ZComponent
in its template because directives
array of Transitive module Y
doesn't contain ZComponent
because YModule
has not imported ZModule
whose transitive module contains ZComponent
in exportedDirectives
array.
Within XComponent
template we can use ZComponent
because Transitive module X
has directives array that contains ZComponent
because
XModule
imports module (YModule
) that exports module (ZModule
) that exports directive ZComponent
Within AppComponent
template we can't use XComponent
because AppModule
imports XModule
but XModule
doesn't exports XComponent
.
See also
-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.
-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.
-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).
Compare the following differences:
/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root
/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root
/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET
I recommend you to look at the adbroker package of the oVirt project. It uses Spring-Ldap and the Krb5 JAAS Login module (with GSSAPI) in order to authenticate using Kerberos against Ldap servers (Active-Directory, ipa, rhds, Tivoli-DS). Look for the code at engine\backend\manager\modules\bll\src\main\java\org\ovirt\engine\core\bll\adbroker
You can use git to clone the repository or browse using the gerrit link
if it is becoming repetitive work ; i think you shud do code reuse ! why dont you simply write functions that "write" small building blocks of HTML. get the idea? see Eg. you can have a function to which you could pass a string and it would automatically put that into a paragraph tag and present it. Of course you would also need to write some kind of a basic parser to do this (how would the function know where to attach the paragraph!). i dont think you are a beginner .. so i am not elaborating ... do tell me if you do not understand..
HashMap supports both null
keys and values
http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
... and permits null values and the null key
So your problem is probably not the map itself.
To append to this famous question (though a bit too late): You can also do df.groupby('column_name').get_group('column_desired_value').reset_index()
to make a new data frame with specified column having a particular value. E.g.
import pandas as pd
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split()})
print("Original dataframe:")
print(df)
b_is_two_dataframe = pd.DataFrame(df.groupby('B').get_group('two').reset_index()).drop('index', axis = 1)
#NOTE: the final drop is to remove the extra index column returned by groupby object
print('Sub dataframe where B is two:')
print(b_is_two_dataframe)
Run this gives:
Original dataframe:
A B
0 foo one
1 bar one
2 foo two
3 bar three
4 foo two
5 bar two
6 foo one
7 foo three
Sub dataframe where B is two:
A B
0 foo two
1 foo two
2 bar two
October 2017
I would like to add another Bootstrap 4 solution. One that worked for me.
The CSS "Order" property, combined with a media query, can be used to re-order columns when they get stacked in smaller screens.
Something like this:
@media only screen and (max-width: 768px) {
#first {
order: 2;
}
#second {
order: 4;
}
#third {
order: 1;
}
#fourth {
order: 3;
}
}
CodePen Link: https://codepen.io/preston206/pen/EwrXqm
Adjust the screen size and you'll see the columns get stacked in a different order.
I'll tie this in with the original poster's question. With CSS, the navbar, sidebar, and content can be targeted and then order properties applied within a media query.
Local variables are located on the stack. Heap space is occupied by objects.
You can use the -Xmx
option.
Basically heap space is used up everytime you allocate a new object with new
and freed some time after the object is no longer referenced. So make sure that you don't keep references to objects that you no longer need.
It stands for permanent generation:
The permanent generation is special because it holds meta-data describing user classes (classes that are not part of the Java language). Examples of such meta-data are objects describing classes and methods and they are stored in the Permanent Generation. Applications with large code-base can quickly fill up this segment of the heap which will cause
java.lang.OutOfMemoryError
: PermGen no matter how high your -Xmx and how much memory you have on the machine.
I know it is usually considered only for testing but you could use the Hamcrest JSON comparitorSameJSONAs in Hamcrest JSON.
int mHours = t / 60; //since both are ints, you get an int
int mMinutes = t % 60;
System.out.printf("%d:%02d", "" +mHours, "" +mMinutes);
These are the values from Bootstrap3:
/* Extra Small */
@media(max-width:767px){}
/* Small */
@media(min-width:768px) and (max-width:991px){}
/* Medium */
@media(min-width:992px) and (max-width:1199px){}
/* Large */
@media(min-width:1200px){}
I'd like to add the following to Shay Levy's correct answer:
You can make your life easier if you create a little batch script run.cmd
to launch your powershell script:
@echo off & setlocal
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC"
Put it in the same path as SQLExecutor.ps1
and from now on you can run it by simply double-clicking on run.cmd
.
Note:
If you require command line arguments inside the run.cmd batch, simply pass them as %1
... %9
(or use %*
to pass all parameters) to the powershell script, i.e.
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*
The variable batchPath
contains the executing path of the batch file itself (this is what the expression %~dp0
is used for). So you just put the powershell script in the same path as the calling batch file.
My team and I ran into this error, unable to update local ref, when doing a pull in SourceTree.
Update 2020: Per @Edward Yang's answer below, @bryan's comment on this answer, and this question/answer you may need to run both
git gc --prune=now
andgit remote prune origin
. Running only the former has always worked for me but based on ppl's responses I think both are necessary to address different causes of the error.
We used:
git gc --prune=now
This removes any duplicate reference objects which should fix the issue.
Here are a few links where you can learn more about git references and pruning :
Have you tried the -0
option in xargs? Something like this:
ls -r1 | xargs -0 grep 'some text'
There are two things to take care of:
Get a helper function that returns a Illuminate\Http\Request
and call the ->ip()
method:
request()->ip();
Think of your server configuration, it may use a proxy or load-balancer
, especially in an AWS ELB configuration.
If this is your case you need to follow "Configuring Trusted Proxies" or maybe even set a "Trusting All Proxies" option.
Why? Because being your server will be getting your proxy/load-balancer
IP instead.
If you are on the AWS balance-loader, go to App\Http\Middleware\TrustProxies
and make $proxies
declaration look like this:
protected $proxies = '*';
Now test it and celebrate because you just saved yourself from having trouble with throttle middleware. It also relies on request()->ip()
and without setting "TrustProxies" up, you could have all your users blocked from logging in instead of blocking only the culprit's IP.
And because throttle middleware is not explained properly in the documentation, I recommend watching "laravel 5.2 tutorial for beginner, API Rate Limiting"
Tested in Laravel 5.7
The following solution works for Android Marshmallow 6 (API 23, API 24, API 25, API 26, API 27, API 28). It also works in Xamarin.
LatLngBounds.Builder builder = new LatLngBounds.Builder();
//the include method will calculate the min and max bound.
builder.include(marker1.getPosition());
builder.include(marker2.getPosition());
builder.include(marker3.getPosition());
builder.include(marker4.getPosition());
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.10); // offset from edges of the map 10% of screen
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
mMap.animateCamera(cu);
If you have a string variable with \n
in it, that you want to put inside td
, you can try
<td>
{value
.split('\n')
.map((s, index) => (
<React.Fragment key={index}>
{s}
<br />
</React.Fragment>
))}
</td>
(Firstly read the other answers which has explained the for
in the <label></label>
tags.
Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1"
but with different ids id="r1_1" ... id="r1_2"
So this way the answer is more clear and removes the conflicts between name and ids as well.
You need different ids for different options of the radio box.
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
<label for="r1_1">button text one</label>_x000D_
<br/>_x000D_
<input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
<label for="r1_2">button text two</label>_x000D_
<br/>_x000D_
<input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
<label for="r1_3">button text three</label>
_x000D_
In Java 8, you can use the new forEachRemaining
method that's been added to the Iterator
interface:
List<Element> list = new ArrayList<>();
iterator.forEachRemaining(list::add);
here is a quick review and with a simple and quick understanding
from teacher Beau Carnes from freecodecamp
As you can see in the Java Source of the java.lang.String class:
/**
* Allocates a new <code>String</code> that contains characters from
* a subarray of the character array argument. The <code>offset</code>
* argument is the index of the first character of the subarray and
* the <code>count</code> argument specifies the length of the
* subarray. The contents of the subarray are copied; subsequent
* modification of the character array does not affect the newly
* created string.
*
* @param value array that is the source of characters.
* @param offset the initial offset.
* @param count the length.
* @exception IndexOutOfBoundsException if the <code>offset</code>
* and <code>count</code> arguments index characters outside
* the bounds of the <code>value</code> array.
*/
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = new char[count];
this.count = count;
System.arraycopy(value, offset, this.value, 0, count);
}
Parameter references are surrounded by <code></code>
tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).
Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
You can try to use the following code instead:
$pro= model_name::where('col_name', '=', 'value')->get();
I had a similar problem, too: I wanted numbers and null on an input field that is not required. Worked through a number of different variations. I finally settled on this one, which seems to do the trick. You place a Directive, ntvFormValidity
, on any form control that has native invalidity and that doesn't swizzle that invalid state into ng-invalid.
Sample use:
<input type="number" formControlName="num" placeholder="0" ntvFormValidity>
Directive definition:
import { Directive, Host, Self, ElementRef, AfterViewInit } from '@angular/core';
import { FormControlName, FormControl, Validators } from '@angular/forms';
@Directive({
selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {
constructor(@Host() private cn: FormControlName, @Host() private el: ElementRef) { }
/*
- Angular doesn't fire "change" events for invalid <input type="number">
- We have to check the DOM object for browser native invalid state
- Add custom validator that checks native invalidity
*/
ngAfterViewInit() {
var control: FormControl = this.cn.control;
// Bridge native invalid to ng-invalid via Validators
const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
const v_fn = control.validator;
control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
setTimeout(()=>control.updateValueAndValidity(), 0);
}
}
The challenge was to get the ElementRef from the FormControl so that I could examine it. I know there's @ViewChild, but I didn't want to have to annotate each numeric input field with an ID and pass it to something else. So, I built a Directive which can ask for the ElementRef.
On Safari, for the HTML example above, Angular marks the form control invalid on inputs like "abc".
I think if I were to do this over, I'd probably build my own CVA for numeric input fields as that would provide even more control and make for a simple html.
Something like this:
<my-input-number formControlName="num" placeholder="0">
PS: If there's a better way to grab the FormControl for the directive, I'm guessing with Dependency Injection and providers
on the declaration, please let me know so I can update my Directive (and this answer).
You need to log in with the correct username and password. Does the user root have permission to access the database? or did you create a specific user to do this?
The other issue might be that you are not using a password when trying to log in.
Here's mine:
set statusline=
set statusline +=%1*\ %n\ %* "buffer number
set statusline +=%5*%{&ff}%* "file format
set statusline +=%3*%y%* "file type
set statusline +=%4*\ %<%F%* "full path
set statusline +=%2*%m%* "modified flag
set statusline +=%1*%=%5l%* "current line
set statusline +=%2*/%L%* "total lines
set statusline +=%1*%4v\ %* "virtual column number
set statusline +=%2*0x%04B\ %* "character under cursor
And here's the colors I used:
hi User1 guifg=#eea040 guibg=#222222
hi User2 guifg=#dd3333 guibg=#222222
hi User3 guifg=#ff66ff guibg=#222222
hi User4 guifg=#a0ee40 guibg=#222222
hi User5 guifg=#eeee40 guibg=#222222
You use a self join when a table references data in itself.
E.g., an Employee
table may have a SupervisorID
column that points to the employee that is the boss of the current employee.
To query the data and get information for both people in one row, you could self join like this:
select e1.EmployeeID,
e1.FirstName,
e1.LastName,
e1.SupervisorID,
e2.FirstName as SupervisorFirstName,
e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID
Here's a quick way to preview a large table without having it run too wide:
Display function:
# display large dataframes in an html iframe
def ldf_display(df, lines=500):
txt = ("<iframe " +
"srcdoc='" + df.head(lines).to_html() + "' " +
"width=1000 height=500>" +
"</iframe>")
return IPython.display.HTML(txt)
Now just run this in any cell:
ldf_display(large_dataframe)
This will convert the dataframe to html then display it in an iframe. The advantage is that you can control the output size and have easily accessible scroll bars.
Worked for my purposes, maybe it will help someone else.
How to Update table and column in mvc using entity framework code
first approach
1: tool > package manager console
2: select current project where context class exist
3: Enable migration using following command
PM > enable-migrations
4: Add migration folder name using following command
PM > add-migration MyMigrationName
4: Now update database following command
PM > update-database
.modal {
text-align: center;
}
@media screen and (min-width: 768px) {
.modal:before {
display: inline-block;
vertical-align: middle;
content: " ";
height: 100%;
}
}
.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}
And adjust a little bit .fade class to make sure it appears out of the top border of window, instead of center
You can add "issue time" to token and maintain "last logout time" for each user on the server. When you check token validity, also check "issue time" be after "last logout time".
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
The in
operator only works on objects. You are using it on a string. Make sure your value is an object before you using $.each
. In this specific case, you have to parse the JSON:
$.each(JSON.parse(myData), ...);
SELECT *
FROM my_table
WHERE substr(my_field,1,5) = "abcde";
Plain Java 8 solutions using a Stream
.
Assuming private Collection<T> c, c2, c3
.
One solution:
public Stream<T> stream() {
return Stream.concat(Stream.concat(c.stream(), c2.stream()), c3.stream());
}
Another solution:
public Stream<T> stream() {
return Stream.of(c, c2, c3).flatMap(Collection::stream);
}
Assuming private Collection<Collection<T>> cs
:
public Stream<T> stream() {
return cs.stream().flatMap(Collection::stream);
}
You're close
sudo apt-get install php-xml
Then you need to restart apache so it takes effect
sudo service apache2 restart
Roll your own. For example, just model your tree as list of list. You should detail your specific need before people can provide better recommendation.
In response to HelloGoodbye's question, this is a sample code to iterate a tree.
def walk(node):
""" iterate tree in pre-order depth-first search order """
yield node
for child in node.children:
for n in walk(child):
yield n
One catch is this recursive implementation is O(n log n). It works fine for all trees I have to deal with. Maybe the subgenerator in Python 3 would help.
Others have already offered good explanations, but I thought I should clarify the differences between the various extensions:
Source Files for C: .c Header Files for C: .h Source Files for C++: .cpp Header Files for C++: .hpp
Of course, as it has already been pointed out, these are just conventions. The compiler doesn't actually pay any attention to them - it's purely for the benefit of the coder.
You can set height and width like this also:
viewinstance.setLayoutParams(new LayoutParams(width, height));
This works:
<img src="invalid_link"
onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
>
Live demo: http://jsfiddle.net/oLqfxjoz/
As Nikola pointed out in the comment below, in case the backup URL is invalid as well, some browsers will trigger the "error" event again which will result in an infinite loop. We can guard against this by simply nullifying the "error" handler via this.onerror=null;
.
I strongly suggest you to read this blog post which appeared on HackerNews recently: How HashMap works in Java
In short, the answer is
What will happen if two different HashMap key objects have same hashcode?
They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap.
Say there is a url as follows
http://localhost:3000/callback?code=6c3c9b39-de2f-3bf4-a542-3e77a64d3341
If we want to extract the code from that URL, below method will work.
const authResult = new URLSearchParams(window.location.search);
const code = authResult.get('code')
You can use Linq to XML to do this:
XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
let attr = node.Attribute("name")
where attr != null && attr.Value == "File1"
select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");
You can use:
set content=
for /f "delims=" %%i in ('type text.txt') do set content=!content! %%i
I'd just drop the database and then re-create it. On a UNIX or Linux system, that should do it:
$ dropdb development_db_name
$ createdb developmnent_db_name
That's how I do it, actually.
The integer math solution that Ian provided is nice, but suffers from an integer overflow bug. Assuming the variables are all int
, the solution could be rewritten to use long
math and avoid the bug:
int pageCount = (-1L + records + recordsPerPage) / recordsPerPage;
If records
is a long
, the bug remains. The modulus solution does not have the bug.
Simply use
var xmlString = '<?xml version="1.0" ?><root />';
var xml = jQuery.parseXML(xml);
It's jQuery.parseXML, so no need to worry about cross-browser tricks. Use jQuery as like HTML, it's using the native XML engine.
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
var output = [a.slice(0, position), b, a.slice(position)].join('');_x000D_
console.log(output);
_x000D_
The following can be used to splice text
within another string at a desired index
, with an optional removeCount
parameter.
if (String.prototype.splice === undefined) {_x000D_
/**_x000D_
* Splices text within a string._x000D_
* @param {int} offset The position to insert the text at (before)_x000D_
* @param {string} text The text to insert_x000D_
* @param {int} [removeCount=0] An optional number of characters to overwrite_x000D_
* @returns {string} A modified string containing the spliced text._x000D_
*/_x000D_
String.prototype.splice = function(offset, text, removeCount=0) {_x000D_
let calculatedOffset = offset < 0 ? this.length + offset : offset;_x000D_
return this.substring(0, calculatedOffset) +_x000D_
text + this.substring(calculatedOffset + removeCount);_x000D_
};_x000D_
}_x000D_
_x000D_
let originalText = "I want apple";_x000D_
_x000D_
// Positive offset_x000D_
console.log(originalText.splice(6, " an"));_x000D_
// Negative index_x000D_
console.log(originalText.splice(-5, "an "));_x000D_
// Chaining_x000D_
console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.
Writing that much data to a file is going to take a while.
You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).
You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?
You should also write a function to do the calculation; you could use an inline
function in C99 or later (or C++). The repetition in the code is excruciating to behold.
You should also use C99 notation for main()
, with the explicit return type (and preferably void
for the argument list when you are not using argc
or argv
):
int main(void)
Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 };
(thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static
in front of the functions, and the main array; file
becomes a local to main
; error check the fopen()
, etc.).
I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.
#include <stdio.h>
#define lambda 2.0
#define g 1.0
#define F0 1.0
#define h 0.1
#define e 0.00001
enum { ROWS = 1000, COLS = 10000 };
static double F[ROWS][COLS];
static void Inicio(double D[ROWS][COLS])
{
for (int i = 399; i < 600; i++) // Magic numbers!!
D[i][0] = F0;
}
enum { R = ROWS - 1 };
static inline int ko(int k, int n)
{
int rv = k + n;
if (rv >= R)
rv -= R;
else if (rv < 0)
rv += R;
return(rv);
}
static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
int ks2 = ko(k, -2);
int ks1 = ko(k, -1);
int kp1 = ko(k, +1);
int kp2 = ko(k, +2);
A[k][i] = A[k][i-1]
+ e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
+ 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
+ e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}
static void Iteration(double A[ROWS][COLS])
{
for (int i = 1; i < COLS; i++)
{
for (int k = 0; k < R; k++)
calculate_value(i, k, A);
A[999][i] = A[0][i];
}
}
int main(void)
{
FILE *file = fopen("P2.txt","wt");
if (file == 0)
return(1);
Inicio(F);
Iteration(F);
for (int i = 0; i < COLS; i++)
{
for (int j = 0; j < ROWS; j++)
{
fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
}
}
fclose(file);
return(0);
}
This program writes to P2.txt
instead of P1.txt
. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:
Original Modified
6.334s 6.367s
6.241s 6.231s
6.315s 10.778s
6.378s 6.320s
6.388s 6.293s
6.285s 6.268s
6.387s 10.954s
6.377s 6.227s
8.888s 6.347s
6.304s 6.286s
6.258s 10.302s
6.975s 6.260s
6.663s 6.847s
6.359s 6.313s
6.344s 6.335s
7.762s 6.533s
6.310s 9.418s
8.972s 6.370s
6.383s 6.357s
However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for
loop became:
for (int i = COLS - 1; i < COLS; i++)
the timings were vastly reduced and very much more consistent:
Original Modified
0.168s 0.165s
0.145s 0.165s
0.165s 0.166s
0.164s 0.163s
0.151s 0.151s
0.148s 0.153s
0.152s 0.171s
0.165s 0.165s
0.173s 0.176s
0.171s 0.165s
0.151s 0.169s
The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.
If the task you want to pass parameters to is of type JavaExec
and you are using Gradle 5, for example the application plugin's run
task, then you can pass your parameters through the --args=...
command line option. For example gradle run --args="foo --bar=true"
.
Otherwise there is no convenient builtin way to do this, but there are 3 workarounds.
If the possible values are few and are known in advance, you can programmatically create a task for each of them:
void createTask(String platform) {
String taskName = "myTask_" + platform;
task (taskName) {
... do what you want
}
}
String[] platforms = ["macosx", "linux32", "linux64"];
for(String platform : platforms) {
createTask(platform);
}
You would then call your tasks the following way:
./gradlew myTask_macosx
A convenient hack is to pass the arguments through standard input, and have your task read from it:
./gradlew myTask <<<"arg1 arg2 arg\ in\ several\ parts"
with code below:
String[] splitIntoTokens(String commandLine) {
String regex = "(([\"']).*?\\2|(?:[^\\\\ ]+\\\\\\s+)+[^\\\\ ]+|\\S+)";
Matcher matcher = Pattern.compile(regex).matcher(commandLine);
ArrayList<String> result = new ArrayList<>();
while (matcher.find()) {
result.add(matcher.group());
}
return result.toArray();
}
task taskName, {
doFirst {
String typed = new Scanner(System.in).nextLine();
String[] parsed = splitIntoTokens(typed);
println ("Arguments received: " + parsed.join(" "))
... do what you want
}
}
You will also need to add the following lines at the top of your build script:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
The last option is to pass a -P
parameter to Gradle:
./gradlew myTask -PmyArg=hello
You can then access it as myArg
in your build script:
task myTask {
doFirst {
println myArg
... do what you want
}
}
Credit to @789 for his answer on splitting arguments into tokens
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
application.statusBarHidden = YES;
return YES;
}
If your application uses async stuff and you're fiddling with Mouse's cursor, you probably want to do it only in main UI thread. You can use app's Dispatcher thread for that:
Application.Current.Dispatcher.Invoke(() =>
{
// The check is required to prevent cursor flickering
if (Mouse.OverrideCursor != cursor)
Mouse.OverrideCursor = cursor;
});
Place them inside of the success:
of the one it relies on.
$.ajax({
url: 'http://www.xxxxxxxxxxxxx',
data: {name: 'xxxxxx'},
dataType: 'jsonp',
success: function(data){
// do stuff
// call next ajax function
$.ajax({ xxx });
}
});
Typically a .sh file is a shell script which you can execute in a terminal. Specifically, the script you mentioned is a bash script, which you can see if you open the file and look in the first line of the file, which is called the shebang or magic line.
In your Jenkins job configuration, tick the box named "This build is parameterized
", click the "Add Parameter
" button and select the "String Parameter
" drop down value.
Now define your parameter - example:
Now you can use your parameter in your job / build pipeline, example:
Next to trigger the build with own/custom parameter, invoke the following URL (using either POST or GET):
http://JENKINS_SERVER_ADDRESS/job/YOUR_JOB_NAME/buildWithParameters?myparam=myparam_value
Add this line above you Query
SET IDENTITY_INSERT tbl_content ON
Very short ES6 functions using template literals. Be aware that you need to encode/decode the values by yourself but it'll work out of the box for simplier purposes like storing version numbers.
const getCookie = (cookieName) => {
return (document.cookie.match(`(^|;) *${cookieName}=([^;]*)`)||[])[2]
}
const setCookie = (cookieName, value, days=360, path='/') => {
let expires = (new Date(Date.now()+ days*86400*1000)).toUTCString();
document.cookie = `${cookieName}=${value};expires=${expires};path=${path};`
}
const deleteCookie = (cookieName) => {
document.cookie = `${cookieName}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;`;
}
In my case I was using the prototype name as the object name. For e.g.
function proto1()
{}
var proto1 = new proto1();
It was a silly mistake but might be of help to someone like me ;)
found the solution with AND condition:
$trainstrength = "UPDATE user_character SET strength_trains = strength_trains + 1, trained_strength = trained_strength +1, character_gold = character_gold - $gold_to_next_strength WHERE ID = $currentUser AND character_gold > $gold_to_next_strength";
Iteration is synonymous with sprint, sprint is just the Scrum terminology.
On the question about sprint length, the only caution I would note is that in Scrum you are using the past sprints to gain a level of predictability on your teams ability to deliver on their commitments for the sprint. They do this by developing a velocity over a number of sprints. A change in the team members or the length of the sprint are factors that will affect the velocity for a sprint, over past sprints.
Just as background, velocity is the sum of estimation points assigned to the backlog items, or stories, that were completely finished during that sprint. Most Agile proponents (Mike Cohn, Ken Schwaber and Jeff Sutherland for instance), recommend that teams use "the recent weather" to base their future estimations on how much they think they can commit to in a sprint. This means using the average from the last few sprints as the basis for an estimate in the upcoming sprint planning session.
Once again, varying the sprint length reduces your teams ability to provide that velocity statistic which the team uses for sprint planning, and the product owner uses for release planning (i.e. predicting when the project will end or what will be in the project at the end).
I recommend Mike Cohn's book on Agile Estimating and Planning to provide an overview of the way sprints, estimation and planning all can fit together.
use the following commands instead:
ALTER TABLE table_name DISABLE TRIGGER tr_name
ALTER TABLE table_name ENABLE TRIGGER tr_name
I think it will be easier using syntax-based query:
var entryPoint = (from ep in dbContext.tbl_EntryPoint
join e in dbContext.tbl_Entry on ep.EID equals e.EID
join t in dbContext.tbl_Title on e.TID equals t.TID
where e.OwnerID == user.UID
select new {
UID = e.OwnerID,
TID = e.TID,
Title = t.Title,
EID = e.EID
}).Take(10);
And you should probably add orderby
clause, to make sure Top(10)
returns correct top ten items.
You must sort your data according your needs (es. in reverse order) and use select top query
How about this ? checking for length of undefined array may throw exception.
if(image_array){
//array exists
if(image_array.length){
//array has length greater than zero
}
}
You're probably using
document.getElementById('element').innerHTML = "New content"
Try this instead:
document.getElementById('element').innerHTML += "New content"
Or, preferably, use DOM Manipulation:
document.getElementById('element').appendChild(document.createElement("div"))
Dom manipulation would be preferred compared to using innerHTML
, because innerHTML
simply dumps a string into the document. The browser will have to reparse the entire document to get it's stucture.
ES6
With the new class and extend keywords it’s now much easier:
class CustomError extends Error {
constructor(message) {
super(message);
//something
}
}
git config --global fetch.prune true
To always --prune
for git fetch
and git pull
in all your Git repositories:
git config --global fetch.prune true
This above command appends in your global Git configuration (typically ~/.gitconfig
) the following lines. Use git config -e --global
to view your global configuration.
[fetch]
prune = true
git config remote.origin.prune true
To always --prune
but from one single repository:
git config remote.origin.prune true
#^^^^^^
#replace with your repo name
This above command adds in your local Git configuration (typically .git/config
) the below last line. Use git config -e
to view your local configuration.
[remote "origin"]
url = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
fetch = +refs/heads/*:refs/remotes/origin/*
prune = true
You can also use --global
within the second command or use instead --local
within the first command.
git config --global gui.pruneDuringFetch true
If you use git gui
you may also be interested by:
git config --global gui.pruneDuringFetch true
that appends:
[gui]
pruneDuringFetch = true
The corresponding documentations from git help config
:
--global
For writing options: write to global
~/.gitconfig
file rather than the repository.git/config
, write to$XDG_CONFIG_HOME/git/config
file if this file exists and the~/.gitconfig
file doesn’t.
--local
For writing options: write to the repository
.git/config
file. This is the default behavior.
fetch.prune
If true, fetch will automatically behave as if the
--prune
option was given on the command line. See alsoremote.<name>.prune
.
gui.pruneDuringFetch
"true" if git-gui should prune remote-tracking branches when performing a fetch. The default value is "false".
remote.<name>.prune
When set to true, fetching from this remote by default will also remove any remote-tracking references that no longer exist on the remote (as if the
--prune
option was given on the command line). Overridesfetch.prune
settings, if any.
Using the same as approach as Romeo, I adapted it to Visual Studio 2010 :
<None Condition=" '$(Configuration)' == 'Debug' " Include="appDebug\App.config" />
<None Condition=" '$(Configuration)' == 'Release' " Include="appRelease\App.config" />
Here you need to keep both App.config files in different directories (appDebug and appRelease). I tested it and it works fine!
I think you are looking for:
$result->isEmpty()
This is different from empty($result)
, which will not be true because the result will be an empty collection. Your suggestion of count($result)
is also a good solution. I cannot find any reference in the docs
you should do import Map from './Map'
React is just telling you it doesn't know where variable you are importing is.
Try setting 'clientCredentialType' to 'Windows' instead of 'Ntlm'.
I think that this is what the server is expecting - i.e. when it says the server expects "Negotiate,NTLM", that actually means Windows Auth, where it will try to use Kerberos if available, or fall back to NTLM if not (hence the 'negotiate')
I'm basing this on somewhat reading between the lines of: Selecting a Credential Type
First you have to include the file you call:
#!/bin/bash
. includes/included_file.sh
then you call your function like this:
#!/bin/bash
my_called_function
Add a background Drawable like res/drawables/background.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/white" />
<stroke android:width="1dp" android:color="@android:color/black" />
</shape>
Update the ImageView background in res/layout/foo.xml:
...
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="1dp"
android:background="@drawable/background"
android:src="@drawable/bar" />
...
Exclude the ImageView padding if you want the src to draw over the background.
I've got the same error. I have been trying to fixing this by setting higher permission to account running SQL Client service, however it didnt help. The problem was that I run MS Sql Management studio just within my account. So, next time... assure that you are running it as Run as Administrator, if using Win7 with UAC enabled.
Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs
Yes, yes yes.
The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.
In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].
Be careful when you take the exception object or the traceback object out of the exception handler, since this causes circular references and gc.collect()
will fail to collect. This appears to be of a particular problem in the ipython/jupyter notebook environment where the traceback object doesn't get cleared at the right time and even an explicit call to gc.collect()
in finally
section does nothing. And that's a huge problem if you have some huge objects that don't get their memory reclaimed because of that (e.g. CUDA out of memory exceptions that w/o this solution require a complete kernel restart to recover).
In general if you want to save the traceback object, you need to clear it from references to locals()
, like so:
import sys, traceback, gc
type, val, tb = None, None, None
try:
myfunc()
except:
type, val, tb = sys.exc_info()
traceback.clear_frames(tb)
# some cleanup code
gc.collect()
# and then use the tb:
if tb:
raise type(val).with_traceback(tb)
In the case of jupyter notebook, you have to do that at the very least inside the exception handler:
try:
myfunc()
except:
type, val, tb = sys.exc_info()
traceback.clear_frames(tb)
raise type(val).with_traceback(tb)
finally:
# cleanup code in here
gc.collect()
Tested with python 3.7.
p.s. the problem with ipython or jupyter notebook env is that it has %tb
magic which saves the traceback and makes it available at any point later. And as a result any locals()
in all frames participating in the traceback will not be freed until the notebook exits or another exception will overwrite the previously stored backtrace. This is very problematic. It should not store the traceback w/o cleaning its frames. Fix submitted here.
int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";
hope this help! :)
This is a very simple solution for windows forms if all is needed is the final value as a (string). The items' names will be displayed on the Combo Box and the selected value can be easily compared.
List<string> items = new List<string>();
// populate list with test strings
for (int i = 0; i < 100; i++)
items.Add(i.ToString());
// set data source
testComboBox.DataSource = items;
and on the event handler get the value (string) of the selected value
string test = testComboBox.SelectedValue.ToString();
I recommend you use:
var returnedData = JSON.parse(data);
to convert the JSON string (if it is just text) to a JavaScript object.
To Start Tomcat7 Service :
Open cmd, go to bin directory within "Apache Tomcat 7" folder. You will see some this like C:\..\bin>
Enter above command to start the service: C:\..\bin>service.bat install
. The service will get started now.
Enter above command to start tomcat7w monitory service. If you have issue with starting the tomcat7 service then remove the service with command : C:\..\bin>tomcat7 //DS//Tomcat7
Now the service will no longer exist. Try the install command again, now the service will get installed and started: C:\..\bin>tomcat7w \\MS\tomcat7w
You will see the tomcat 7 icon in the system tray. Now, the tomcat7 service and tomcat7w will start automatically when the windows get start.
When you modify a file in your repository, the change is initially unstaged. In order to commit it, you must stage it—that is, add it to the index—using git add
. When you make a commit, the changes that are committed are those that have been added to the index.
git reset
changes, at minimum, where the current branch (HEAD
) is pointing. The difference between --mixed
and --soft
is whether or not your index is also modified. So, if we're on branch master
with this series of commits:
- A - B - C (master)
HEAD
points to C
and the index matches C
.
When we run git reset --soft B
, master
(and thus HEAD
) now points to B
, but the index still has the changes from C
; git status
will show them as staged. So if we run git commit
at this point, we'll get a new commit with the same changes as C
.
Okay, so starting from here again:
- A - B - C (master)
Now let's do git reset --mixed B
. (Note: --mixed
is the default option). Once again, master
and HEAD
point to B, but this time the index is also modified to match B
. If we run git commit
at this point, nothing will happen since the index matches HEAD
. We still have the changes in the working directory, but since they're not in the index, git status
shows them as unstaged. To commit them, you would git add
and then commit as usual.
And finally, --hard
is the same as --mixed
(it changes your HEAD
and index), except that --hard
also modifies your working directory. If we're at C
and run git reset --hard B
, then the changes added in C
, as well as any uncommitted changes you have, will be removed, and the files in your working copy will match commit B
. Since you can permanently lose changes this way, you should always run git status
before doing a hard reset to make sure your working directory is clean or that you're okay with losing your uncommitted changes.
And finally, a visualization: