How about something based on Douglas Crockford idea:
function Shape(){}
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function(){
return this.constructor.parent
? this.constructor.parent.toString() + ',' + this.name
: this.name;
};
function TwoDShape(){}
var F = function(){};
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.parent = Shape.prototype;
TwoDShape.prototype.name = '2D Shape';
var my = new TwoDShape();
console.log(my.toString()); ===> Shape,2D Shape
.NET is seeing an invalid SSL certificate on the other end of the connection. There is a workaround for it, but obviously not recommended for production code:
// Put this somewhere that is only once - like an initialization method
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate);
...
static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
Every browser has some default styles that apply to a number of HTML elements, likes p and ul. The space you mention is likely created because of the default margin and padding of your browser. You can reset these though:
p { margin: 0; padding: 0; }
ul { margin: 0; padding: 0; }
You could also reset all default margins and paddings:
* { margin: 0; padding: 0; }
I suggest you take a look at normalize.css: http://necolas.github.com/normalize.css/
String s1 = "Welcome"; // Does not create a new instance
String s2 = new String("Welcome"); // Creates two objects and one reference variable
While many options above function well, I found coercion of non-target variables to chr
problematic. Using ifelse
and grepl
within lapply
resolves this off-target effect (in limited testing). Using slarky's regular expression in grepl
:
set.seed(42)
x1 <- sample(c("a","b"," ", "a a", NA), 10, TRUE)
x2 <- sample(c(rnorm(length(x1),0, 1), NA), length(x1), TRUE)
df <- data.frame(x1, x2, stringsAsFactors = FALSE)
The problem of coercion to character class:
df2 <- lapply(df, function(x) gsub("^$|^ $", NA, x))
lapply(df2, class)
$x1
[1] "character"
$x2 [1] "character"
Resolution with use of ifelse:
df3 <- lapply(df, function(x) ifelse(grepl("^$|^ $", x)==TRUE, NA, x))
lapply(df3, class)
$x1
[1] "character"
$x2 [1] "numeric"
Note that in the Java implementation, the number of bits to shift is mod'd by the size of the source.
For example:
(long) 4 >> 65
equals 2. You might expect shifting the bits to the right 65 times would zero everything out, but it's actually the equivalent of:
(long) 4 >> (65 % 64)
This is true for <<, >>, and >>>. I have not tried it out in other languages.
Try writing the file path as "C:\\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener"
i.e with double backslash after the drive as opposed to "C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener"
It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.
<input id="myFileInput" type="file" accept="image/*;capture=camera">
var myInput = document.getElementById('myFileInput');
function sendPic() {
var file = myInput.files[0];
// Send file here either by adding it to a `FormData` object
// and sending that via XHR, or by simply passing the file into
// the `send` method of an XHR instance.
}
myInput.addEventListener('change', sendPic, false);
Create a .gitignore file in include all files and directories that you don't want to commit.
Example:
#################
## Eclipse
#################
*.pydevproject
.project
.metadata
.gradle
bin/
tmp/
target/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
#################
## Visual Studio
#################
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
x64/
build/
[Bb]in/
[Oo]bj/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.log
*.scc
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.Publish.xml
*.pubxml
# NuGet Packages Directory
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
#packages/
# Windows Azure Build Output
csx
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.[Pp]ublish.xml
*.pfx
*.publishsettings
what is the best way to do this in C++?
Because you asked it this way:
std::string msg(65546, 0); // all characters will be set to 0
Or:
std::vector<char> msg(65546); // all characters will be initialized to 0
If you are working with C functions which accept char* or const char*, then you can do:
some_c_function(&msg[0]);
You can also use the c_str() method on std::string if it accepts const char* or data().
The benefit of this approach is that you can do everything you want to do with a dynamically allocating char buffer but more safely, flexibly, and sometimes even more efficiently (avoiding the need to recompute string length linearly, e.g.). Best of all, you don't have to free the memory allocated manually, as the destructor will do this for you.
public static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
TCP is appropriate when you have to move a decent amount of data (> ~1 kB), and you require all of it to be delivered. Almost all data that moves across the internet does so via TCP - HTTP, SMTP, BitTorrent, SSH, etc, all use TCP.
UDP is appropriate when you have small messages which you can afford to lose, and would like to send them as efficiently as possible. One reason you might be able to afford to lose them is because you can re-send them if they get lost. The main example on the internet is DNS - DNS consists of small queries saying things like "what is the IP number for stackoverflow.com?", and the responses are correspondingly small. Computers make a lot of these queries, so they should be made efficiently, but if they get lost en route, it's easy to time out and re-send them.
If this is your code, the correct solution is to rewrite it to not use Session()
, since that's no longer necessary in TensorFlow 2
If this is just code you're running, you can downgrade to TensorFlow 1 by running
pip3 install --upgrade --force-reinstall tensorflow-gpu==1.15.0
(or whatever the latest version of TensorFlow 1 is)
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action
to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
I have used it in this way and it works for me. https://msdn.microsoft.com/en-us/library/system.web.caching.cache.add(v=vs.110).aspx parameters info for system.web.caching.cache.add.
public string GetInfo()
{
string name = string.Empty;
if(System.Web.HttpContext.Current.Cache["KeyName"] == null)
{
name = GetNameMethod();
System.Web.HttpContext.Current.Cache.Add("KeyName", name, null, DateTime.Noew.AddMinutes(5), Cache.NoSlidingExpiration, CacheitemPriority.AboveNormal, null);
}
else
{
name = System.Web.HttpContext.Current.Cache["KeyName"] as string;
}
return name;
}
Use Prim's algorithm when you have a graph with lots of edges.
For a graph with V vertices E edges, Kruskal's algorithm runs in O(E log V) time and Prim's algorithm can run in O(E + V log V) amortized time, if you use a Fibonacci Heap.
Prim's algorithm is significantly faster in the limit when you've got a really dense graph with many more edges than vertices. Kruskal performs better in typical situations (sparse graphs) because it uses simpler data structures.
This worked for me
<select ng-init="basicProfile.casteId" ng-model="basicProfile.casteId" class="form-control">
<option value="0">Select Caste....</option>
<option data-ng-repeat="option in formCastes" value="{{option.id}}">{{option.casteName}}</option>
</select>
profilage bas� sur l'analyse de l'esprit
(french)
should be translated as:
profilage basé sur l'analyse de l'esprit
so, in this case �
= é
You could use this function:
function RefreshTable(tableId, urlData)
{
//Retrieve the new data with $.getJSON. You could use it ajax too
$.getJSON(urlData, null, function( json )
{
table = $(tableId).dataTable();
oSettings = table.fnSettings();
table.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
Dont' forget to call it after your delete function has succeded.
Two issues:
You're passing the jQuery wrapper of the element into parseInt
, which isn't what you want, as parseInt
will call toString
on it and get back "[object Object]"
. You need to use val
or text
or something (depending on what the element is) to get the string you want.
You're not telling parseInt
what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt
guesses which radix to use.
Fix if the element is a form field:
// vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
Fix if the element is something else and you want to use the text within it:
// vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
You probably need to some plugin like Jquery multiselect dropdown. Here is a demo.
Also you need to close your option tags like this:
<select name="test" multiple>
<option>123</option>
<option>456</option>
<option>789</option>
</select>
To test an android apps in a real device with Android Studio, You must keep two things in mind
Now , let me tell you how you can enable USB debugging on your android phone:
Now let me tell you how you can download the driver on your Windows PC:
Probably the easiest way to explore your ElasticSearch cluster is to use elasticsearch-head.
You can install it by doing:
cd elasticsearch/
./bin/plugin -install mobz/elasticsearch-head
Then (assuming ElasticSearch is already running on your local machine), open a browser window to:
http://localhost:9200/_plugin/head/
Alternatively, you can just use curl
from the command line, eg:
Check the mapping for an index:
curl -XGET 'http://127.0.0.1:9200/my_index/_mapping?pretty=1'
Get some sample docs:
curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1'
See the actual terms stored in a particular field (ie how that field has been analyzed):
curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1' -d '
{
"facets" : {
"my_terms" : {
"terms" : {
"size" : 50,
"field" : "foo"
}
}
}
}
More available here: http://www.elasticsearch.org/guide
By far the easiest way of writing curl
-style commands for Elasticsearch is the Sense plugin in Marvel.
It comes with source highlighting, pretty indenting and autocomplete.
Note: Sense was originally a standalone chrome plugin but is now part of the Marvel project.
/**
* Removes one instance of `value` from `array`, without mutating the original array. Uses loose comparison.
*
* @param {Array} array Array to remove value from
* @param {*} value Value to remove
* @returns {Array} Array with `value` removed
*/
export function arrayRemove(array, value) {
for(let i=0; i<array.length; ++i) {
if(array[i] == value) {
let copy = [...array];
copy.splice(i, 1);
return copy;
}
}
return array;
}
For 20% transparency, this worked for me:
Button bu = (Button)findViewById(R.id.button1);
bu.getBackground().setAlpha(204);
I had same issue. I found the answer:
ini_set('memory_limit', '-1');
Update: Use this carefully as this might slow down your system if the PHP script starts using an excessive amount of memory, causing a lot of swap space usage. You can use this if you know program will not take much memory and also you don't know how much to set it right now. But you will eventually find it how much memory you require for that program.
You should always memory limit as some value as answered by @sarki dinle
.
ini_set('memory_limit', '512M');
In my case I had a similar problem but with c ++ this in windows 10, the problem was solved by adding the environment variables (path) windows, the folder of the c ++ libraries, in my case I used the codeblock libraries:
C:\codeblocks\MinGW\bin
find supports wildcard matches, just add a *
:
find / -type d -name "ora10*"
$property_images = $_FILES['property_images']['name'];
if(!empty($property_images))
{
for($up=0;$up<count($property_images);$up++)
{
move_uploaded_file($_FILES['property_images']['tmp_name'][$up],'../images/property_images/'.$_FILES['property_images']['name'][$up]);
}
}
I had from a totaly different reason the same notice "Value does not fall within the expected range" from the Visual studio 2008 while trying to use the: Tools -> Windows Embedded Silverlight Tools -> Update Silverlight For Windows Embedded Project.
After spending many ohurs I found out that the problem was that there wasn't a resource file and the update tool looks for the .RC file
Therefor the solution is to add to the resource folder a .RC file and than it works perfectly. I hope it will help someone out there
Read about request objects that your views receive: https://docs.djangoproject.com/en/dev/ref/request-response/#httprequest-objects
Also your hidden field needs a reliable name and then a value:
<input type="hidden" name="title" value="{{ source.title }}">
Then in a view:
request.POST.get("title", "")
In Python 3.2.2, I found \Python32\Lib\idlelib\idle.bat
which was useful because it would let me open python files supplied as args in IDLE.
I've solved it, it can be done executing:
netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33
To remove forwarding:
netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111
You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.
Based only on your style you would have:
<a href="home.com" id="logo"></a>
1) Also you can use lateinit
If you sure do your initialization later on onCreate()
or elsewhere.
Use this
lateinit var left: Node
Instead of this
var left: Node? = null
2) And there is other way that use !!
end of variable when you use it like this
queue.add(left!!) // add !!
Because &
has a lesser priority than ==
.
Your code is equivalent to a[0] & (1 == 0)
, and unless a[0]
is a boolean this won't compile...
You need to:
(a[0] & 1) == 0
etc etc.
(yes, Java does hava a boolean &
operator -- a non shortcut logical and)
Here's a little function that will do "NATO encoding" for you:
CREATE FUNCTION dbo.NATOEncode (
@String varchar(max)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN (
WITH L1 (N) AS (SELECT 1 UNION ALL SELECT 1),
L2 (N) AS (SELECT 1 FROM L1, L1 B),
L3 (N) AS (SELECT 1 FROM L2, L2 B),
L4 (N) AS (SELECT 1 FROM L3, L3 B),
L5 (N) AS (SELECT 1 FROM L4, L4 C),
L6 (N) AS (SELECT 1 FROM L5, L5 C),
Nums (Num) AS (SELECT Row_Number() OVER (ORDER BY (SELECT 1)) FROM L6)
SELECT
NATOString = Substring((
SELECT
Convert(varchar(max), ' ' + D.Word)
FROM
Nums N
INNER JOIN (VALUES
('A', 'Alpha'),
('B', 'Beta'),
('C', 'Charlie'),
('D', 'Delta'),
('E', 'Echo'),
('F', 'Foxtrot'),
('G', 'Golf'),
('H', 'Hotel'),
('I', 'India'),
('J', 'Juliet'),
('K', 'Kilo'),
('L', 'Lima'),
('M', 'Mike'),
('N', 'November'),
('O', 'Oscar'),
('P', 'Papa'),
('Q', 'Quebec'),
('R', 'Romeo'),
('S', 'Sierra'),
('T', 'Tango'),
('U', 'Uniform'),
('V', 'Victor'),
('W', 'Whiskey'),
('X', 'X-Ray'),
('Y', 'Yankee'),
('Z', 'Zulu'),
('0', 'Zero'),
('1', 'One'),
('2', 'Two'),
('3', 'Three'),
('4', 'Four'),
('5', 'Five'),
('6', 'Six'),
('7', 'Seven'),
('8', 'Eight'),
('9', 'Niner')
) D (Digit, Word)
ON Substring(@String, N.Num, 1) = D.Digit
WHERE
N.Num <= Len(@String)
FOR XML PATH(''), TYPE
).value('.[1]', 'varchar(max)'), 2, 2147483647)
);
This function will work on even very long strings, and performs pretty well (I ran it against a 100,000-character string and it returned in 589 ms). Here's an example of how to use it:
SELECT NATOString FROM dbo.NATOEncode('LD-23DSP-1430');
-- Output: Lima Delta Two Three Delta Sierra Papa One Four Three Zero
I intentionally made it a table-valued function so it could be inlined into a query if you run it against many rows at once, just use CROSS APPLY
or wrap the above example in parentheses to use it as a value in the SELECT
clause (you can put a column name in the function parameter position).
Have a look at this sample:
public class A {
//statements
}
public class B extends A {
public void foo() { }
}
A a=new B();
//To execute **foo()** method.
((B)a).foo();
more flexible way is a function with two parameters:
function lchar($str,$val){return strlen($str)<=$val?$str:substr($str,0,$val).'...';}
usage:
echo lchar($str,200);
SyncToy is a free application from Microsoft with a "Preview" mode for comparing two paths. For example:
You can then choose one of three modes ("Synchronize", "Echo" and "Contribute") to resolve the differences.
Lastly, it comes with SyncToyCmd
for creating and synchronizing folder pairs from the CLI or a Scheduled Task.
$(document).ready(function(){_x000D_
_x000D_
$(".btn1").click(function(){_x000D_
$("div.test:not(:first)").hide();_x000D_
});_x000D_
_x000D_
$(".btn2").click(function(){_x000D_
$("div.test").show();_x000D_
$("div.test:not(:first):not(:last)").hide();_x000D_
});_x000D_
_x000D_
$(".btn3").click(function(){_x000D_
$("div.test").hide();_x000D_
$("div.test:not(:first):not(:last)").show();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button class="btn1">Hide All except First</button>_x000D_
<button class="btn2">Hide All except First & Last</button>_x000D_
<button class="btn3">Hide First & Last</button>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<div class='test'>First</div>_x000D_
<div class='test'>Second</div>_x000D_
<div class='test'>Third</div>_x000D_
<div class='test'>Last</div>
_x000D_
Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.
Yes. You can use java.util.formatter. You can use a formatting string like "%10.2f"
There is Effort which is an in memory entity framework database provider. I've not actually tried it... Haa just spotted this was mentioned in the question!
Alternatively you could switch to EntityFrameworkCore which has an in memory database provider built-in.
https://github.com/tamasflamich/effort
I used a factory to get a context, so i can create the context close to its use. This seems to work locally in visual studio but not on my TeamCity build server, not sure why yet.
return new MyContext(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;");
You can use import data with wizard and there you can choose destination table.
Run the wizard. In selecting source tables and views window you see two parts. Source and Destination.
Click on the field under Destination part to open the drop down and select you destination table and edit its mappings if needed.
EDIT
Merely typing the name of the table does not work. It appears that the name of the table must include the schema (dbo
) and possibly brackets. Note the dropdown on the right hand side of the text field.
I had a similar problem. Here is what I did. Since the element I was trying to center vertically had height = 60px, I managed to center it vertically using:
top: calc(50% - 30px);
Instead of setBackgroundColor
, retrieve the background drawable and set its color:
v.setBackgroundResource(R.drawable.tags_rounded_corners);
GradientDrawable drawable = (GradientDrawable) v.getBackground();
if (i % 2 == 0) {
drawable.setColor(Color.RED);
} else {
drawable.setColor(Color.BLUE);
}
Also, you can define the padding within your tags_rounded_corners.xml
:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="4dp" />
<padding
android:top="2dp"
android:left="2dp"
android:bottom="2dp"
android:right="2dp" />
</shape>
.joins
will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again
:includes
will eager load the included associations and add them in memory. :includes
loads all the included tables attributes. If you call associations on include query result, it will not fire any queries
I used this code to fix the issue of displaying items in the horizontal list.
new Container(
height: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: array.length,
itemBuilder: (context, index){
return array[index];
},
),
],
),
);
This will search every column of every table in a specific database. Create the stored procedure on the database that you want to search in.
The Ten Most Asked SQL Server Questions And Their Answers:
CREATE PROCEDURE FindMyData_String
@DataToFind NVARCHAR(4000),
@ExactMatch BIT = 0
AS
SET NOCOUNT ON
DECLARE @Temp TABLE(RowId INT IDENTITY(1,1), SchemaName sysname, TableName sysname, ColumnName SysName, DataType VARCHAR(100), DataFound BIT)
INSERT INTO @Temp(TableName,SchemaName, ColumnName, DataType)
SELECT C.Table_Name,C.TABLE_SCHEMA, C.Column_Name, C.Data_Type
FROM Information_Schema.Columns AS C
INNER Join Information_Schema.Tables AS T
ON C.Table_Name = T.Table_Name
AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
WHERE Table_Type = 'Base Table'
And Data_Type In ('ntext','text','nvarchar','nchar','varchar','char')
DECLARE @i INT
DECLARE @MAX INT
DECLARE @TableName sysname
DECLARE @ColumnName sysname
DECLARE @SchemaName sysname
DECLARE @SQL NVARCHAR(4000)
DECLARE @PARAMETERS NVARCHAR(4000)
DECLARE @DataExists BIT
DECLARE @SQLTemplate NVARCHAR(4000)
SELECT @SQLTemplate = CASE WHEN @ExactMatch = 1
THEN 'If Exists(Select *
From ReplaceTableName
Where Convert(nVarChar(4000), [ReplaceColumnName])
= ''' + @DataToFind + '''
)
Set @DataExists = 1
Else
Set @DataExists = 0'
ELSE 'If Exists(Select *
From ReplaceTableName
Where Convert(nVarChar(4000), [ReplaceColumnName])
Like ''%' + @DataToFind + '%''
)
Set @DataExists = 1
Else
Set @DataExists = 0'
END,
@PARAMETERS = '@DataExists Bit OUTPUT',
@i = 1
SELECT @i = 1, @MAX = MAX(RowId)
FROM @Temp
WHILE @i <= @MAX
BEGIN
SELECT @SQL = REPLACE(REPLACE(@SQLTemplate, 'ReplaceTableName', QUOTENAME(SchemaName) + '.' + QUOTENAME(TableName)), 'ReplaceColumnName', ColumnName)
FROM @Temp
WHERE RowId = @i
PRINT @SQL
EXEC SP_EXECUTESQL @SQL, @PARAMETERS, @DataExists = @DataExists OUTPUT
IF @DataExists =1
UPDATE @Temp SET DataFound = 1 WHERE RowId = @i
SET @i = @i + 1
END
SELECT SchemaName,TableName, ColumnName
FROM @Temp
WHERE DataFound = 1
GO
To run it, just do this:
exec FindMyData_string 'google', 0
It works amazingly well!!!
but I need results where r.text is not duplicated
Sounds as if you want this:
table1.GroupBy(x => x.Text)
.Where(g => g.Count() == 1)
.Select(g => g.First());
This will select rows where the Text
is unique.
I have not tried, but if you know Perl you can use the Parse-Stata-DtaReader module to convert the file for you.
The module has a command-line tool dta2csv, which can "convert Stata 8 and Stata 10 .dta files to csv"
You need to:
Go to cloud.google.com
Go to my Console
Choose your Project
Choose Networking > VPC network
Choose "Firewalls rules"
Choose "Create Firewall Rule"
To apply the rule to select VM instances, select Targets > "Specified target tags", and enter into "Target tags" the name of the tag. This tag will be used to apply the new firewall rule onto whichever instance you'd like. Then, make sure the instances have the network tag applied.
To allow incoming TCP connections to port 9090, in "Protocols and Ports" enter tcp:9090
Click Create
I hope this helps you.
Update Please refer to docs to customize your rules.
My issue was that I had overlapping names in the file paths for different types, like this:
<cache-path
name="cached_files"
path="." />
<external-cache-path
name="cached_files"
path="." />
After I changed the names ("cached_files") to be unique, I got rid of the error. My guess is that those paths are stored in some HashMap or something which does not allow duplicates.
If the application is already open (even in background), it will be restored by "start" command. Exit the program if running then /max or /min will work
df[df['col'].astype(bool)]
Empty strings are falsy, which means you can filter on bool values like this:
df = pd.DataFrame({
'A': range(5),
'B': ['foo', '', 'bar', '', 'xyz']
})
df
A B
0 0 foo
1 1
2 2 bar
3 3
4 4 xyz
df['B'].astype(bool)
0 True
1 False
2 True
3 False
4 True
Name: B, dtype: bool
df[df['B'].astype(bool)]
A B
0 0 foo
2 2 bar
4 4 xyz
If your goal is to remove not only empty strings, but also strings only containing whitespace, use str.strip
beforehand:
df[df['B'].str.strip().astype(bool)]
A B
0 0 foo
2 2 bar
4 4 xyz
.astype
is a vectorised operation, this is faster than every option presented thus far. At least, from my tests. YMMV.
Here is a timing comparison, I've thrown in some other methods I could think of.
Benchmarking code, for reference:
import pandas as pd
import perfplot
df1 = pd.DataFrame({
'A': range(5),
'B': ['foo', '', 'bar', '', 'xyz']
})
perfplot.show(
setup=lambda n: pd.concat([df1] * n, ignore_index=True),
kernels=[
lambda df: df[df['B'].astype(bool)],
lambda df: df[df['B'] != ''],
lambda df: df[df['B'].replace('', np.nan).notna()], # optimized 1-col
lambda df: df.replace({'B': {'': np.nan}}).dropna(subset=['B']),
],
labels=['astype', "!= ''", "replace + notna", "replace + dropna", ],
n_range=[2**k for k in range(1, 15)],
xlabel='N',
logx=True,
logy=True,
equality_check=pd.DataFrame.equals)
In Zend Framework 2.0 i had this problem. Can be solved in two way .htaccess or php header i prefer .htaccess so i modified .htaccess from:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
to
RewriteEngine On
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
and it start to work
You can override the constructor. Something like:
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
public MyAsyncTask(boolean showLoading) {
super();
// do stuff
}
// doInBackground() et al.
}
Then, when calling the task, do something like:
new MyAsyncTask(true).execute(maybe_other_params);
Edit: this is more useful than creating member variables because it simplifies the task invocation. Compare the code above with:
MyAsyncTask task = new MyAsyncTask();
task.showLoading = false;
task.execute();
Why the loop?
You could simply do this:
{% if 'priority' in data %}
<p>Priority: {{ data['priority'] }}</p>
{% endif %}
When you were originally doing your string comparison, you should have used ==
instead.
I know this question has already been answered, but I came here looking for a way to filter elements in an Array based on some criteria. So here is my solution example: using select
, I find all constants in Class that start with "RUBY_"
Class.constants.select {|c| c.to_s =~ /^RUBY_/ }
UPDATE: In the meantime I have discovered that Array#grep works much better. For the above example,
Class.constants.grep /^RUBY_/
did the trick.
I had same problem and solution was obj = ClassName.objects.filter()
First is understanding that RFID is very generic term. NFC is subset of RFID technology. NFC is used for prox card, credit cards, tap and go payment system. Your phones can read and emulate NFC (Apple pay, Google pay, etc.), if they support NFC. NFC is very short distance and low power - which is why you see tap and go type usage.
The more common RFID are the tags you see here and there. They come in a wide ranges of styles, uses and frequency.
HF - high frequency tags are what they use for "chipping" animals - cattle, dogs, cats. Read range is about 12 inches and requires an external antenna that is powered the bigger the antenna the more power it needs and the further it can read.
UFH tags look similar to HF tags but have a read range of several feet.
Also HF tags come single read and multi read. UFH is exclusviely multi read.
Mutiread means when a reader is active, you can litterally read about 1700 tags in under 10 seconds.
But this is a function of the size of the antenna and how much power you can push through the reader.
As to the direct question about Android and RFID - the best way to go is to get an external handheld reader that connects to your mobile device via Bluetooth. Bluetooth libraries exist for all mobile devices - Android, Apple, Windows. From there its just a matter of the manufacturer documentation about how to open a socket to the reader and how to decode the serial information.
The TSL line of readers is very popular because you don't have to deal with reading bytes and all that low level serial jazz that other manufactures do. They have a nice set of commands that are easy to use to control the reader.
Other manufactures are basic in that you open a serial socket and then read the output like you would see in terminal app like PuTTY.
Your @JsonSubTypes
declaration does not make sense: it needs to list implementation (sub-) classes, NOT the class itself (which would be pointless). So you need to modify that entry to list sub-class(es) there are; or use some other mechanism to register sub-classes (SimpleModule
has something like addAbstractTypeMapping
).
As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below
git ls-files -z | xargs -0 rm
git checkout -- .
or one line
git ls-files -z | xargs -0 rm ; git checkout -- .
I use it all the time and haven't found any down sides yet!
For some further explanation, the -z
appends a null character onto the end of each entry output by ls-files
, and the -0
tells xargs
to delimit the output it was receiving by those null characters.
this seems to work fine :
dataframe.axes[0].tolist()
I have shared a demo that demonstrates how to cancel an AJAX request-- if data is not returned from the server within a predefined wait time.
HTML :
<div id="info"></div>
JS CODE:
var isDataReceived= false, waitTime= 1000;
$(function() {
// Ajax request sent.
var xhr= $.ajax({
url: 'http://api.joind.in/v2.1/talks/10889',
data: {
format: 'json'
},
dataType: 'jsonp',
success: function(data) {
isDataReceived= true;
$('#info').text(data.talks[0].talk_title);
},
type: 'GET'
});
// Cancel ajax request if data is not loaded within 1sec.
setTimeout(function(){
if(!isDataReceived)
xhr.abort();
},waitTime);
});
<div class="d-flex justify-content-center align-items-center container ">
<div class="row ">
<form action="">
<div class="form-group">
<label for="inputUserName" class="control-label">Enter UserName</label>
<input type="email" class="form-control" id="inputUserName" aria-labelledby="emailnotification">
<small id="emailnotification" class="form-text text-muted">Enter Valid Email Id</small>
</div>
<div class="form-group">
<label for="inputPassword" class="control-label">Enter Password</label>
<input type="password" class="form-control" id="inputPassword" aria-labelledby="passwordnotification">
</div>
</form>
</div>
</div>
You should set andrid:allowRetainTaskState="true" to Launch Activity in Manifest.xml. If this Activty is not Launch Activity. you should set android:launchMode="singleTask" at this activity
For reference, a non-CSS solution:
Below is some JS that re-sizes a font depending on the text length within a container.
Codepen with slightly modified code, but same idea as below:
function scaleFontSize(element) {
var container = document.getElementById(element);
// Reset font-size to 100% to begin
container.style.fontSize = "100%";
// Check if the text is wider than its container,
// if so then reduce font-size
if (container.scrollWidth > container.clientWidth) {
container.style.fontSize = "70%";
}
}
For me, I call this function when a user makes a selection in a drop-down, and then a div in my menu gets populated (this is where I have dynamic text occurring).
scaleFontSize("my_container_div");
In addition, I also use CSS ellipses ("...") to truncate yet even longer text too, like so:
#my_container_div {
width: 200px; /* width required for text-overflow to work */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
So, ultimately:
Short text: e.g. "APPLES"
Fully rendered, nice big letters.
Long text: e.g. "APPLES & ORANGES"
Gets scaled down 70%, via the above JS scaling function.
Super long text: e.g. "APPLES & ORANGES & BANAN..."
Gets scaled down 70% AND gets truncated with a "..." ellipses, via the above JS scaling function together with the CSS rule.
You could also explore playing with CSS letter-spacing to make text narrower while keeping the same font size.
I also found another way of doing this that gives proper 'x10(superscript)5' notation on the axes. I'm posting it here in the hope it might be useful to some. I got the code from here so I claim no credit for it, that rightly goes to Brian Diggs.
fancy_scientific <- function(l) {
# turn in to character string in scientific notation
l <- format(l, scientific = TRUE)
# quote the part before the exponent to keep all the digits
l <- gsub("^(.*)e", "'\\1'e", l)
# turn the 'e+' into plotmath format
l <- gsub("e", "%*%10^", l)
# return this as an expression
parse(text=l)
}
Which you can then use as
ggplot(data=df, aes(x=x, y=y)) +
geom_point() +
scale_y_continuous(labels=fancy_scientific)
Simple code to change all in layout of item (custom listview extends baseadapter):
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
RelativeLayout layout=(RelativeLayout) arg1.findViewById(R.id.rel_cell_left);
layout.setBackgroundColor(Color.YELLOW);
}
});
I had the same error and fixed it. It turned out to be a silly reason.
This was the culprit:
<script src="app.js"/>
Fix:
<script src="app.js"></script>
Make sure your script tag is ended properly!
I had huge problems with this
First I tried .clear()
then I tried .destroy()
and I tried setting my chart reference to null
What finally fixed the issue for me: deleting the <canvas>
element and then reappending a new <canvas>
to the parent container
There's a million ways to do this:
var resetCanvas = function () {
$('#results-graph').remove(); // this is my <canvas> element
$('#graph-container').append('<canvas id="results-graph"><canvas>');
canvas = document.querySelector('#results-graph'); // why use jQuery?
ctx = canvas.getContext('2d');
ctx.canvas.width = $('#graph').width(); // resize to parent width
ctx.canvas.height = $('#graph').height(); // resize to parent height
var x = canvas.width/2;
var y = canvas.height/2;
ctx.font = '10pt Verdana';
ctx.textAlign = 'center';
ctx.fillText('This text is centered on the canvas', x, y);
};
According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.
This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.
select num_rows from all_tables where table_name = 'MY_TABLE'
This query counts the current number of rows in MY_TABLE
select count(*) from my_table
By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.
In the documentation there's an asterisk by the column name, which leads to this note:
Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.
This means that unless you have gathered statistics on the table then this column will not have any data.
Statistics gathered in 11g+ with the default estimate_percent
, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent
less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.
If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.
Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.
Contrary to Martin's answer, casting to int (or ignoring the warning) isn't always safe even if you know your array doesn't have more than 2^31-1 elements. Not when compiling for 64-bit.
For example:
NSArray *array = @[@"a", @"b", @"c"];
int i = (int) [array indexOfObject:@"d"];
// indexOfObject returned NSNotFound, which is NSIntegerMax, which is LONG_MAX in 64 bit.
// We cast this to int and got -1.
// But -1 != NSNotFound. Trouble ahead!
if (i == NSNotFound) {
// thought we'd get here, but we don't
NSLog(@"it's not here");
}
else {
// this is what actually happens
NSLog(@"it's here: %d", i);
// **** crash horribly ****
NSLog(@"the object is %@", array[i]);
}
Try add it on AppDelegate.swift (inside application method):
UITabBar.appearance().tintColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
// For WHITE color:
UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
Example:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Tab bar icon selected color
UITabBar.appearance().tintColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
// For WHITE color: UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
return true
}
Example:
My english is so bad! I'm sorry! :-)
If you're using TortoiseGit then follow the below steps:
TortoiseGit -> Settings
Git -> Remote
origin
URL
text box value to where ever your new remote repository isYour branch and all your local commits will remain intact and you can keep working as you were before.
For AspNetCore, it looks like this:
<aspNetCore requestTimeout="00:20:00">
from __future__ import with_statement
with open('file.txt','r+') as f:
counter = str(int(f.read().strip())+1)
f.seek(0)
f.write(counter)
Generally speaking, in the presence of a garbage collector, it is never good practice to manually call the GC. A GC is organized around heuristic algorithms which work best when left to their own devices. Calling the GC manually often decreases performance.
Occasionally, in some relatively rare situations, one may find that a particular GC gets it wrong, and a manual call to the GC may then improves things, performance-wise. This is because it is not really possible to implement a "perfect" GC which will manage memory optimally in all cases. Such situations are hard to predict and depend on many subtle implementation details. The "good practice" is to let the GC run by itself; a manual call to the GC is the exception, which should be envisioned only after an actual performance issue has been duly witnessed.
This should do it. You were missing a )
and you only need """
not 4 of them. Also you don't need a elif at the end.
ans=True
while ans:
print("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
ans = None
else:
print("\n Not Valid Choice Try again")
You can simply use URLSearchParams()
.
Lets see we have a page with url:
https://example.com/?product=1&category=game
On that page, you can get the query string using window.location.search
and then extract them with URLSearchParams()
class.
const params = new URLSearchParams(window.location.search)
console.log(params.get('product')
// 1
console.log(params.get('category')
// game
Another example using a dynamic url (not from window.location
), you can extract the url using URL object.
const url = new URL('https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest')
console.log(url.search)
// ?v=6xJ27BtlM0c&ab_channel=FliteTest
This is a simple working snippet:
const urlInput = document.querySelector('input[type=url]')
const keyInput = document.querySelector('input[name=key]')
const button = document.querySelector('button')
const outputDiv = document.querySelector('#output')
button.addEventListener('click', () => {
const url = new URL(urlInput.value)
const params = new URLSearchParams(url.search)
output.innerHTML = params.get(keyInput.value)
})
_x000D_
div {
margin-bottom: 1rem;
}
_x000D_
<div>
<label>URL</label> <br>
<input type="url" value="https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest">
</div>
<div>
<label>Params key</label> <br>
<input type="text" name="key" value="v">
</div>
<div>
<button>Get Value</button>
</div>
<div id="output"></div>
_x000D_
There is an in-built stopword list in NLTK
made up of 2,400 stopwords for 11 languages (Porter et al), see http://nltk.org/book/ch02.html
>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> stop = set(stopwords.words('english'))
>>> sentence = "this is a foo bar sentence"
>>> print([i for i in sentence.lower().split() if i not in stop])
['foo', 'bar', 'sentence']
>>> [i for i in word_tokenize(sentence.lower()) if i not in stop]
['foo', 'bar', 'sentence']
I recommend looking at using tf-idf to remove stopwords, see Effects of Stemming on the term frequency?
My c++ STL
code to initialise 5*3 2-D vector
with zero
#include <iostream>
using namespace std;
#include <vector>
int main()
{// if we wnt to initialise a 2 D vector with 0;
vector<vector<int>> v1(5, vector<int>(3,0));
for(int i=0;i<v1.size();i++)
{
for(int j=0;j<v1[i].size();j++)
cout<<v1[i][j]<<" ";
cout<<endl;
}
}
A check of ibliblio
and java.net
repositories reveal that jmx related jar is not present in either. I think you should manually download jms and install them locally as discussed here.
what I do is here:
in /etc/apt/sources.list, add:
deb http://ftp.de.debian.org/debian sid main
Note:the rjava should be latest version
2 run: sudo apt-get update sudo apt-get install r-cran-rjava
Once update the old version of rjava, then can install rhdfs_1.0.8.
The accepted way to rename a table in Laravel 4 is to use the Schema builder. So you would want to do:
Schema::rename('photos', 'images');
From http://laravel.com/docs/4.2/schema#creating-and-dropping-tables
If you really want to write out a raw SQL query yourself, you can always do:
DB::statement('alter table photos rename to images');
Note: Laravel's DB class also supports running raw SQL select
, insert
, update
, and delete
queries, like:
$users = DB::select('select id, name from users');
For more info, see http://laravel.com/docs/4.2/database#running-queries.
Option1:
To set the ASPNETCORE_ENVIRONMENT environment variable in windows,
Command line - setx ASPNETCORE_ENVIRONMENT "Development"
PowerShell - $Env:ASPNETCORE_ENVIRONMENT = "Development"
For other OS refer this - https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments
Option2:
If you want to set ASPNETCORE_ENVIRONMENT using web.config
then add aspNetCore
like this-
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\MyApplication.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</configuration>
With the help of the of Guido mail provided by @kindall, we can understand the standard import process as trying to find the module in each member of sys.path
, and file as the result of this lookup (more details in PyMOTW Modules and Imports.). So if the module is located in an absolute path in sys.path
the result is absolute, but if it is located in a relative path in sys.path
the result is relative.
Now the site.py
startup file takes care of delivering only absolute path in sys.path
, except the initial ''
, so if you don't change it by other means than setting the PYTHONPATH (whose path are also made absolute, before prefixing sys.path
), you will get always an absolute path, but when the module is accessed through the current directory.
Now if you trick sys.path in a funny way you can get anything.
As example if you have a sample module foo.py
in /tmp/
with the code:
import sys
print(sys.path)
print (__file__)
If you go in /tmp you get:
>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
./foo.py
When in in /home/user
, if you add /tmp
your PYTHONPATH
you get:
>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
/tmp/foo.py
Even if you add ../../tmp
, it will be normalized and the result is the same.
But if instead of using PYTHONPATH
you use directly some funny path
you get a result as funny as the cause.
>>> import sys
>>> sys.path.append('../../tmp')
>>> import foo
['', '/usr/lib/python3.3', .... , '../../tmp']
../../tmp/foo.py
Guido explains in the above cited thread, why python do not try to transform all entries in absolute paths:
we don't want to have to call getpwd() on every import .... getpwd() is relatively slow and can sometimes fail outright,
So your path is used as it is.
I test on a lot of Markdown implementations. The non-breaking space ASCII character
(followed by a blank line) would give a blank line. Repeating this pair would do the job. So far I haven't failed any.
For example:
Hello
world!
I would recommend that you use display: inline;
. float
is screwed up in IE. Here is an example of how I would approach it:
<ul class="side-by-side">
<li>item 1<li>
<li>item 2<li>
<li>item 3<li>
</ul>
and here's the css:
.side-by-side {
width: 100%;
border: 1px solid black;
}
.side-by-side li {
display: inline;
}
Also, if you use floats the ul
will not wrap around the li
's and will instead have a hight of 0 in this example:
.side-by-side li {
float: left;
}
Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!
In simple terms,
static : static
variables are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory
volatile: This keyword is applicable to both class and instance variables.
Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads
Have a look at this article by Javin Paul
to understand volatile variables in a better way.
In absence of volatile
keyword, the value of variable in each thread's stack may be different. By making the variable as volatile
, all threads will get same value in their working memory and memory consistency errors have been avoided.
Here the term variable
can be either static
(class) variable or instance
(object) variable.
Regarding your query :
Anyway a static variable value is also going to be one value for all threads, then why should we go for volatile?
If I need instance
variable in my application, I can't use static
variable. Even in case of static
variable, consistency is not guaranteed due to Thread cache as shown in the diagram.
Using volatile
variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.
What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change => memory consistency errors are still possible with volatile variables. To avoid side effects, you have to use synchronized variables. But there is a better solution in java.
Using simple atomic variable access is more efficient than accessing these variables through synchronized code
Some of the classes in the java.util.concurrent
package provide atomic methods that do not rely on synchronization.
Refer to this high level concurrency control article for more details.
Especially have a look at Atomic variables.
Related SE questions:
I like:
git format-patch HEAD~<N>
where <N>
is number of last commits to save as patches.
The details how to use the command are in the DOC
UPD
Here you can find how to apply them then.
UPD For those who did not get the idea of format-patch
Add alias:
git config --global alias.make-patch '!bash -c "cd ${GIT_PREFIX};git add .;git commit -m ''uncommited''; git format-patch HEAD~1; git reset HEAD~1"'
Then at any directory of your project repository run:
git make-patch
This command will create 0001-uncommited.patch
at your current directory. Patch will contain all the changes and untracked files that are visible to next command:
git status .
A third great alternative is using the package data.table
, which also has the class data.frame, but operations like you are looking for are computed much faster.
library(data.table)
mydt <- structure(list(Name = c("Aira", "Aira", "Aira", "Ben", "Ben", "Ben", "Cat", "Cat", "Cat"), Month = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Rate1 = c(15.6396600443877, 2.15649279424609, 6.24692918928743, 2.37658797276116, 34.7500663272292, 3.28750138697048, 29.3265553981065, 17.9821839334431, 10.8639802575958), Rate2 = c(17.1680489538369, 5.84231656330206, 8.54330866437461, 5.88415184986176, 3.02064294862551, 17.2053351400752, 16.9552950199166, 2.56058000170089, 15.7496228048122)), .Names = c("Name", "Month", "Rate1", "Rate2"), row.names = c(NA, -9L), class = c("data.table", "data.frame"))
Now to take the mean of Rate1 and Rate2 for all 3 months, for each person (Name): First, decide which columns you want to take the mean of
colstoavg <- names(mydt)[3:4]
Now we use lapply to take the mean over the columns we want to avg (colstoavg)
mydt.mean <- mydt[,lapply(.SD,mean,na.rm=TRUE),by=Name,.SDcols=colstoavg]
mydt.mean
Name Rate1 Rate2
1: Aira 8.014361 10.517891
2: Ben 13.471385 8.703377
3: Cat 19.390907 11.755166
Many people had difficulty in using this keyword when we have iteration of Drop-downs with same elements but different values or say as Multi line data in USER INTERFACE. : Here is the code snippet : $(this).find('option[value=yourvalue]');
Hope you got this.
None of these answers seemed simple enough - the crux of the problem is not having to rebuild:
makefile
OBJDIR=out
VPATH=$(OBJDIR)
# make will look in VPATH to see if the target needs to be rebuilt
test: moo
touch $(OBJDIR)/$@
example use
touch moo
# creates out/test
make test
# doesn't update out/test
make test
# will now update test
touch moo
make test
This is the snippet to store environment variable and access it.
node {
withEnv(["ENABLE_TESTS=true", "DISABLE_SQL=false"]) {
stage('Select Jenkinsfile') {
echo "Enable test?: ${env.DEVOPS_SKIP_TESTS}
customStep script: this
}
}
}
Note: The value of environment variable is coming as a String. If you want to use it as a boolean then you have to parse it using Boolean.parse(env.DISABLE_SQL).
To convert seconds time stamp to millisecond time stamp. You could use the TimeUnit API and neat like this.
long milliSecondTimeStamp = MILLISECONDS.convert(secondsTimeStamp, SECONDS)
public static class GlobalVariables
{
// readonly variable
public static string Foo
{
get
{
return "foo";
}
}
// read-write variable
public static string Bar
{
get
{
return HttpContext.Current.Application["Bar"] as string;
}
set
{
HttpContext.Current.Application["Bar"] = value;
}
}
}
When creating the colors, you may use rgb
and set its alpha
argument:
plot(1:10, col = rgb(red = 1, green = 0, blue = 0, alpha = 0.5),
pch = 16, cex = 4)
points((1:10) + 0.4, col = rgb(red = 0, green = 0, blue = 1, alpha = 0.5),
pch = 16, cex = 4)
Please see ?rgb
for details.
I created this table which contains both the heights of iPhone and iPad keyboards, both for landscape and portrait mode, both with the toolbar on and off.
I even explained how you can use these dimensions in your code here.
Note that you should only use these dimensions if you need to know the keyboard's dimension before you layout the view. Otherwise the solutions from the other answers work better.
upgraded MaxU's answer with MultiIndex support
def explode(df, lst_cols, fill_value='', preserve_index=False):
"""
usage:
In [134]: df
Out[134]:
aaa myid num text
0 10 1 [1, 2, 3] [aa, bb, cc]
1 11 2 [] []
2 12 3 [1, 2] [cc, dd]
3 13 4 [] []
In [135]: explode(df, ['num','text'], fill_value='')
Out[135]:
aaa myid num text
0 10 1 1 aa
1 10 1 2 bb
2 10 1 3 cc
3 11 2
4 12 3 1 cc
5 12 3 2 dd
6 13 4
"""
# make sure `lst_cols` is list-alike
if (lst_cols is not None
and len(lst_cols) > 0
and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))):
lst_cols = [lst_cols]
# all columns except `lst_cols`
idx_cols = df.columns.difference(lst_cols)
# calculate lengths of lists
lens = df[lst_cols[0]].str.len()
# preserve original index values
idx = np.repeat(df.index.values, lens)
res = (pd.DataFrame({
col:np.repeat(df[col].values, lens)
for col in idx_cols},
index=idx)
.assign(**{col:np.concatenate(df.loc[lens>0, col].values)
for col in lst_cols}))
# append those rows that have empty lists
if (lens == 0).any():
# at least one list in cells is empty
res = (res.append(df.loc[lens==0, idx_cols], sort=False)
.fillna(fill_value))
# revert the original index order
res = res.sort_index()
# reset index if requested
if not preserve_index:
res = res.reset_index(drop=True)
# if original index is MultiIndex build the dataframe from the multiindex
# create "exploded" DF
if isinstance(df.index, pd.MultiIndex):
res = res.reindex(
index=pd.MultiIndex.from_tuples(
res.index,
names=['number', 'color']
)
)
return res
I think this is what you want:
JavaScriptSerializer JSS = new JavaScriptSerializer();
T obj = JSS.Deserialize<T>(String);
An
in
statement will be parsed identically tofield=val1 or field=val2 or field=val3
. Putting a null in there will boil down tofield=null
which won't work.
I would do this for clairity
SELECT *
FROM tbl_name
WHERE
(id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL)
"Domain" is not a property of an LDAP object. It is more like the name of the database the object is stored in.
So you have to connect to the right database (in LDAP terms: "bind to the domain/directory server") in order to perform a search in that database.
Once you bound successfully, your query in it's current shape is all you need.
BTW: Choosing "ObjectCategory=Person"
over "ObjectClass=user"
was a good decision. In AD, the former is an "indexed property" with excellent performance, the latter is not indexed and a tad slower.
When a
and b
are 1-dimensional sequences, numpy.cov(a,b)[0][1]
is equivalent to your cov(a,b)
.
The 2x2 array returned by np.cov(a,b)
has elements equal to
cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
(where, again, cov
is the function you defined above.)
The str.split
method will automatically remove all white space between items:
>>> str1 = "a b c d"
>>> str1.split()
['a', 'b', 'c', 'd']
Docs are here: http://docs.python.org/library/stdtypes.html#str.split
Months in Calendar object start from 0
0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY
\9 doesn’t work with font-family, instead you’d need to use “\0/ !important” as Chris mentioned above, for example:
p { font-family: Arial \0/ !important; }
This can be done quite easily using javascript XMLHttpRequest() class (AJAX):
function FileHelper()
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
...
var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
Here's the way to extend to variable args when you don't have the args hard coded (although they are still technically hard coded in this example, but should be easy to figure out how to extend...):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int argcount = 3;
const char* args[] = {"1", "2", "3"};
const char* binary_name = "mybinaryname";
char myoutput_array[5000];
sprintf(myoutput_array, "%s", binary_name);
for(int i = 0; i < argcount; ++i)
{
strcat(myoutput_array, " ");
strcat(myoutput_array, args[i]);
}
system(myoutput_array);
Definitely should use a dict using the "group" + str(i) key as described in the accepted solution but I wanted to share a solution using exec. Its a way to parse strings into commands & execute them dynamically. It would allow to create these scalar variable names as per your requirement instead of using a dict. This might help in regards what not to do, and just because you can doesn't mean you should. Its a good solution only if using scalar variables is a hard requirement:
l = locals()
for i in xrange(3):
exec("group" + str(i) + "= self.getGroup(selected, header + i)")
Another example where this could work using a Django model example. The exec alternative solution is commented out and the better way of handling such a case using the dict attribute makes more sense:
Class A(models.Model):
....
def __getitem__(self, item): # a.__getitem__('id')
#exec("attrb = self." + item)
#return attrb
return self.__dict__[item]
It might make more sense to extend from a dictionary in the first place to get setattr and getattr functions.
A situation which involves parsing, for example generating & executing python commands dynamically, exec is what you want :) More on exec here.
def exit(self):
self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)
This worked for me to destroy my Tkinter frame on clicking the exit button.
I wasn't sure what you wanted to do about the Event column, but if you want to keep that as well, how about
isIDmax <- with(dd, ave(Value, ID, FUN=function(x) seq_along(x)==which.max(x)))==1
group[isIDmax, ]
# ID Value Event
# 3 1 5 2
# 7 2 17 2
# 9 3 5 2
Here we use ave
to look at the "Value" column for each "ID". Then we determine which value is the maximal and then turn that into a logical vector we can use to subset the original data.frame.
You also can use special change_table method in the migration for adding new columns:
change_table(:users) do |t|
t.column :email, :string
end
I tested with:
$("div.error").remove();
$(".error").removeClass("error");
It will be ok, when you need to validate it again.
Operator ?.
is not supported in TypeScript version 2.0.
So I use the following function:
export function o<T>(someObject: T, defaultValue: T = {} as T) : T {
if (typeof someObject === 'undefined' || someObject === null)
return defaultValue;
else
return someObject;
}
the usage looks like this:
o(o(o(test).prop1).prop2
plus, you can set a default value:
o(o(o(o(test).prop1).prop2, "none")
It works really well with IntelliSense in Visual Studio.
Spring Boot seems had changed the way of reading the VM options as it evolves. Here's some way to try when you launch an application in Intellij and want to active some profile:
Open "Edit configuration" in "Run", and in "VM options", add: -Dspring.profiles.active=local
It actually works with one project of mine with Spring Boot v2.0.3.RELEASE
and Spring v5.0.7.RELEASE
, but not with another project with Spring Boot v2.1.1.RELEASE
and Spring v5.1.3.RELEASE
.
Also, when running with Maven or JAR, people mentioned this:
mvn spring-boot:run -Drun.profiles=dev
or
java -jar -Dspring.profiles.active=dev XXX.jar
(See here: how to use Spring Boot profiles)
It is mentioned somewhere, that Spring changes the way of launching the process of applications if you specify some JVM options; it forks another process and will not pass the arg it received so this does not work. The only way to pass args to it, is:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="..."
Again, this is for Maven. https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-debug.html
What works for me for the second project, was setting the environment variable, as mentioned in some answer above: "Edit configuration" - "Environment variable", and:
SPRING_PROFILES_ACTIVE=local
Casting should be enough. If you're using C# 3.0 you can make a handy extension method to parse enum values:
public static TEnum ToEnum<TInput, TEnum>(this TInput value)
{
Type type = typeof(TEnum);
if (value == default(TInput))
{
throw new ArgumentException("Value is null or empty.", "value");
}
if (!type.IsEnum)
{
throw new ArgumentException("Enum expected.", "TEnum");
}
return (TEnum)Enum.Parse(type, value.ToString(), true);
}
You have to put file extension here
File file = new File("10_Random.txt");
/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
int result = 0;
Iterator<Row> rowIterator = xssfSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Cell> cells = new ArrayList<>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cells.add(cellIterator.next());
}
for (int i = cells.size(); i >= 0; i--) {
Cell cell = cells.get(i-1);
if (cell.toString().trim().isEmpty()) {
cells.remove(i-1);
} else {
result = cells.size() > result ? cells.size() : result;
break;
}
}
}
return result;
}
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
You have a couple of questions here, so I'll address them separately:
My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).
You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:
Base table (what you have now):
| id primary_key sequence
| -- other columns here.
Items table:
| id primary_key sequence
| descript VARCHAR(30) UNIQUE
Map table:
| base_id bigint
| items_id bigint
Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.
And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.
If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.
Personally, I would use TEXT
. It does not sound like you'd gain much by making this a BLOB
, and TEXT
, in my experience, is easier to read if you're using some form of IDE.
I had this error because I had my files within a package. So my foo package I had to call like:
java foo.HelloWorld
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
Try this:
git rev-parse --short HEAD
The command git rev-parse
can do a remarkable number of different things, so you'd need to go through the documentation very carefully to spot that though.
If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:
string newFileLocation = @"c:\test\Test\SomeFile.txt";
while (File.Exists(newFileLocation)) {
newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(@"c:\test\SomeFile.txt", newFileLocation);
This assumes the only '.' in the file name is before the extension. It splits the file in two before the extension, attaches "_copy." in between. This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)
just use:
window.location.href = "http://siwei.me"
Don't use vue-router, otherwise you will be redirected to "http://yoursite.com/#!/http://siwei.me"
my environment: node 6.2.1, vue 1.0.21, Ubuntu.
And just to provide a contrast, there's also pip.
Check out the library angular-cache if you like $http's built-in caching but want more control. You can use it to seamlessly augment $http cache with time-to-live, periodic purges, and the option of persisting the cache to localStorage so that it's available across sessions.
FWIW, it also provides tools and patterns for making your cache into a more dynamic sort of data-store that you can interact with as POJO's, rather than just the default JSON strings. Can't comment on the utility of that option as yet.
(Then, on top of that, related library angular-data is sort of a replacement for $resource and/or Restangular, and is dependent upon angular-cache.)
select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;
HTH
I resolved the issue via this command
pg_ctl -D /usr/local/var/postgres start
At times, you might get this error
pg_ctl: another server might be running; trying to start server anyway
So, try running the following command and then run the first command given above.
pg_ctl -D /usr/local/var/postgres stop
If you're on windows and using apache, maybe via WAMP or the Drupal stack installer, you can additionally download the git for windows package, which includes many useful linux command line tools, one of which is openssl.
The following command creates the self signed certificate and key needed for apache and works fine in windows:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privatekey.key -out certificate.crt
In my opinion, "pass by value" is a terrible way to singularly describe two similar but different events. I guess they should have asked me first.
With primitives we are passing the actual value of the primitive into the method (or constructor), be it the integer "5", the character "c", or what have you. That actual value then becomes its own local primitive. But with objects, all we are doing is giving the same object an additional reference (a local reference), so that we now have two references pointing to the same object.
I hope this simple explanation helps.
If you want to create directory in windows:
- name: Create directory structure
win_file:
path: C:\Temp\folder\subfolder>
state: directory
EDIT
As of today with flexbox, you could
body {
display:flex; flex-direction:column; justify-content:center;
min-height:100vh;
}
PREVIOUS ANSWER
html, body {height:100%;}
html {display:table; width:100%;}
body {display:table-cell; text-align:center; vertical-align:middle;}
Deleting metadata folder might not work in this case. Or eclipse -clean command. Or reinstall eclipse might not solve this.
Instead try deleting other java versions you might have in your machine.
Check what you have right now using this:
/usr/libexec/java_home -V
Delete other java versions which you don't want, following below command:
sudo rm -rf /System/Library/Java/JavaVirtualMachines/java-version.jdk
This should resolve your issue.
"using MyNamespace" works in MVC3 RTM. Hope this helps.
I had to add [AllowAnonymous] to the ActionResult functions in my login page because the user was not authenticated yet.
You can use rename_axis
, for removing set to None
:
d = {'Index Title': ['Apples', 'Oranges', 'Puppies', 'Ducks'],'Column 1': [1.0, 2.0, 3.0, 4.0]}
df = pd.DataFrame(d).set_index('Index Title')
print (df)
Column 1
Index Title
Apples 1.0
Oranges 2.0
Puppies 3.0
Ducks 4.0
print (df.index.name)
Index Title
print (df.columns.name)
None
The new functionality works well in method chains.
df = df.rename_axis('foo')
print (df)
Column 1
foo
Apples 1.0
Oranges 2.0
Puppies 3.0
Ducks 4.0
You can also rename column names with parameter axis
:
d = {'Index Title': ['Apples', 'Oranges', 'Puppies', 'Ducks'],'Column 1': [1.0, 2.0, 3.0, 4.0]}
df = pd.DataFrame(d).set_index('Index Title').rename_axis('Col Name', axis=1)
print (df)
Col Name Column 1
Index Title
Apples 1.0
Oranges 2.0
Puppies 3.0
Ducks 4.0
print (df.index.name)
Index Title
print (df.columns.name)
Col Name
print df.rename_axis('foo').rename_axis("bar", axis="columns")
bar Column 1
foo
Apples 1.0
Oranges 2.0
Puppies 3.0
Ducks 4.0
print df.rename_axis('foo').rename_axis("bar", axis=1)
bar Column 1
foo
Apples 1.0
Oranges 2.0
Puppies 3.0
Ducks 4.0
From version pandas 0.24.0+
is possible use parameter index
and columns
:
df = df.rename_axis(index='foo', columns="bar")
print (df)
bar Column 1
foo
Apples 1.0
Oranges 2.0
Puppies 3.0
Ducks 4.0
Removing index and columns names means set it to None
:
df = df.rename_axis(index=None, columns=None)
print (df)
Column 1
Apples 1.0
Oranges 2.0
Puppies 3.0
Ducks 4.0
If MultiIndex
in index only:
mux = pd.MultiIndex.from_arrays([['Apples', 'Oranges', 'Puppies', 'Ducks'],
list('abcd')],
names=['index name 1','index name 1'])
df = pd.DataFrame(np.random.randint(10, size=(4,6)),
index=mux,
columns=list('ABCDEF')).rename_axis('col name', axis=1)
print (df)
col name A B C D E F
index name 1 index name 1
Apples a 5 4 0 5 2 2
Oranges b 5 8 2 5 9 9
Puppies c 7 6 0 7 8 3
Ducks d 6 5 0 1 6 0
print (df.index.name)
None
print (df.columns.name)
col name
print (df.index.names)
['index name 1', 'index name 1']
print (df.columns.names)
['col name']
df1 = df.rename_axis(('foo','bar'))
print (df1)
col name A B C D E F
foo bar
Apples a 5 4 0 5 2 2
Oranges b 5 8 2 5 9 9
Puppies c 7 6 0 7 8 3
Ducks d 6 5 0 1 6 0
df2 = df.rename_axis('baz', axis=1)
print (df2)
baz A B C D E F
index name 1 index name 1
Apples a 5 4 0 5 2 2
Oranges b 5 8 2 5 9 9
Puppies c 7 6 0 7 8 3
Ducks d 6 5 0 1 6 0
df2 = df.rename_axis(index=('foo','bar'), columns='baz')
print (df2)
baz A B C D E F
foo bar
Apples a 5 4 0 5 2 2
Oranges b 5 8 2 5 9 9
Puppies c 7 6 0 7 8 3
Ducks d 6 5 0 1 6 0
Removing index and columns names means set it to None
:
df2 = df.rename_axis(index=(None,None), columns=None)
print (df2)
A B C D E F
Apples a 6 9 9 5 4 6
Oranges b 2 6 7 4 3 5
Puppies c 6 3 6 3 5 1
Ducks d 4 9 1 3 0 5
For MultiIndex
in index and columns is necessary working with .names
instead .name
and set by list or tuples:
mux1 = pd.MultiIndex.from_arrays([['Apples', 'Oranges', 'Puppies', 'Ducks'],
list('abcd')],
names=['index name 1','index name 1'])
mux2 = pd.MultiIndex.from_product([list('ABC'),
list('XY')],
names=['col name 1','col name 2'])
df = pd.DataFrame(np.random.randint(10, size=(4,6)), index=mux1, columns=mux2)
print (df)
col name 1 A B C
col name 2 X Y X Y X Y
index name 1 index name 1
Apples a 2 9 4 7 0 3
Oranges b 9 0 6 0 9 4
Puppies c 2 4 6 1 4 4
Ducks d 6 6 7 1 2 8
Plural is necessary for check/set values:
print (df.index.name)
None
print (df.columns.name)
None
print (df.index.names)
['index name 1', 'index name 1']
print (df.columns.names)
['col name 1', 'col name 2']
df1 = df.rename_axis(('foo','bar'))
print (df1)
col name 1 A B C
col name 2 X Y X Y X Y
foo bar
Apples a 2 9 4 7 0 3
Oranges b 9 0 6 0 9 4
Puppies c 2 4 6 1 4 4
Ducks d 6 6 7 1 2 8
df2 = df.rename_axis(('baz','bak'), axis=1)
print (df2)
baz A B C
bak X Y X Y X Y
index name 1 index name 1
Apples a 2 9 4 7 0 3
Oranges b 9 0 6 0 9 4
Puppies c 2 4 6 1 4 4
Ducks d 6 6 7 1 2 8
df2 = df.rename_axis(index=('foo','bar'), columns=('baz','bak'))
print (df2)
baz A B C
bak X Y X Y X Y
foo bar
Apples a 2 9 4 7 0 3
Oranges b 9 0 6 0 9 4
Puppies c 2 4 6 1 4 4
Ducks d 6 6 7 1 2 8
Removing index and columns names means set it to None
:
df2 = df.rename_axis(index=(None,None), columns=(None,None))
print (df2)
A B C
X Y X Y X Y
Apples a 2 0 2 5 2 0
Oranges b 1 7 5 5 4 8
Puppies c 2 4 6 3 6 5
Ducks d 9 6 3 9 7 0
And @Jeff solution:
df.index.names = ['foo','bar']
df.columns.names = ['baz','bak']
print (df)
baz A B C
bak X Y X Y X Y
foo bar
Apples a 3 4 7 3 3 3
Oranges b 1 2 5 8 1 0
Puppies c 9 6 3 9 6 3
Ducks d 3 2 1 0 1 0
If you want to use dynamic variables
This won't work:
{{#each obj[key]}}
...
{{/each}}
You need to do:
{{#each (lookup obj key)}}
...
{{/each}}
If you're using typescript, this could be a good thing for you
enum ETime {
Seconds = 1000,
Minutes = 60000,
Hours = 3600000,
SecInMin = 60,
MinInHours = 60,
HoursMod = 24,
timeMin = 10,
}
interface ITime {
millis: number
modulo: number
}
const Times = {
seconds: {
millis: ETime.Seconds,
modulo: ETime.SecInMin,
},
minutes: {
millis: ETime.Minutes,
modulo: ETime.MinInHours,
},
hours: {
millis: ETime.Hours,
modulo: ETime.HoursMod,
},
}
const dots: string = ":"
const msToTime = (duration: number, needHours: boolean = true): string => {
const getCorrectTime = (divider: ITime): string => {
const timeStr: number = Math.floor(
(duration / divider.millis) % divider.modulo,
)
return timeStr < ETime.timeMin ? "0" + timeStr : String(timeStr)
}
return (
(needHours ? getCorrectTime(Times.hours) + dots : "") +
getCorrectTime(Times.minutes) +
dots +
getCorrectTime(Times.seconds)
)
}
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
You might find the Semantic Versioning Specification useful.
Here is a solution inspired by this answer:
if 'abc' and 'efg' can be on the same line:
grep -zl 'abc.*efg' <your list of files>
if 'abc' and 'efg' must be on different lines:
grep -Pzl '(?s)abc.*\n.*efg' <your list of files>
Params:
-P
Use perl compatible regular expressions (PCRE).
-z
Treat the input as a set of lines, each terminated by a zero byte instead of a newline. i.e. grep treats the input as a one big line.
-l
list matching filenames only.
(?s)
activate PCRE_DOTALL, which means that '.' finds any character or newline.
Regarding your code: It's slightly hard to read... If you want to try to view it all in a php array format, just print_r it. This might help:
<?php
$a =
array(
'languages' =>
array (
76 =>
array ( 'id' => '76', 'tag' => 'Deutsch', ), ), 'targets' =>
array ( 81 =>
array ( 'id' => '81', 'tag' => 'Deutschland', ), ), 'tags' =>
array ( 7866 =>
array ( 'id' => '7866', 'tag' => 'automobile', ), 17800 =>
array ( 'id' => '17800', 'tag' => 'seat leon', ), 17801 =>
array ( 'id' => '17801', 'tag' => 'seat leon cupra', ), ),
'inactiveTags' =>
array ( 195 =>
array ( 'id' => '195', 'tag' => 'auto', ), 17804 =>
array ( 'id' => '17804', 'tag' => 'coupès', ), 17805 =>
array ( 'id' => '17805', 'tag' => 'fahrdynamik', ), 901 =>
array ( 'id' => '901', 'tag' => 'fahrzeuge', ), 17802 =>
array ( 'id' => '17802', 'tag' => 'günstige neuwagen', ), 1991 =>
array ( 'id' => '1991', 'tag' => 'motorsport', ), 2154 =>
array ( 'id' => '2154', 'tag' => 'neuwagen', ), 10660 =>
array ( 'id' => '10660', 'tag' => 'seat', ), 17803 =>
array ( 'id' => '17803', 'tag' => 'sportliche ausstrahlung', ), 74 =>
array ( 'id' => '74', 'tag' => 'web 2.0', ), ), 'categories' =>
array ( 16082 =>
array ( 'id' => '16082', 'tag' => 'Auto & Motorrad', ), 51 =>
array ( 'id' => '51', 'tag' => 'Blogosphäre', ), 66 =>
array ( 'id' => '66', 'tag' => 'Neues & Trends', ), 68 =>
array ( 'id' => '68', 'tag' => 'Privat', ), ), );
printarr($a);
printarr($a['languages'][76]['tag']);
parintarr($a['targets'][81]['id']);
function printarr($in){
echo "\n";
print_r($in);
echo "\n";
}
//run in php command line php path/to/file.php to test, switching otu the print_r.
because:
Static
: as we can't have objects of interfaces so we should avoid using Object level member variables and should use class level variables i.e. static.
Final
: so that we should not have ambiguous values for the variables(Diamond problem - Multiple Inheritance).
And as per the documentation interface is a contract and not an implementation.
reference: Abhishek Jain's answer on quora
Non-evil C, assuming the common case where the string is a null-terminated char
array:
#include <stddef.h>
#include <string.h>
/* PRE: str must be either NULL or a pointer to a
* (possibly empty) null-terminated string. */
void strrev(char *str) {
char temp, *end_ptr;
/* If str is NULL or empty, do nothing */
if( str == NULL || !(*str) )
return;
end_ptr = str + strlen(str) - 1;
/* Swap the chars */
while( end_ptr > str ) {
temp = *str;
*str = *end_ptr;
*end_ptr = temp;
str++;
end_ptr--;
}
}
begin transaction
// execute SQL code here
rollback transaction
If you've already executed the query and want to roll it back, unfortunately your only real option is to restore a database backup. If you're using Full backups, then you should be able to restore the database to a specific point in time.
Hey i'm using Volley and was getting Server error 411, I added to the getHeaders method the following line :
params.put("Content-Length","0");
And it solved my issue
You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
If the customer does not exist, you'll get an sql exception which text will be something like:
null value in column "customer_id" violates not-null constraint
(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:
insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.
This is a joke for those who are excited about the JavaScript frameworks and do not know the pure Javascript.
So VanillaJS is the same as pure Javascript.
Vanilla in slang means:
unexciting, normal, conventional, boring
Here is a nice presentation on YouTube about VanillaJS: What is Vanilla JS?
uses a text type but forces the appearance of the numeric keyboard
<input value="12,4" type="text" inputmode="numeric" pattern="[-+]?[0-9]*[.,]?[0-9]+">
the inputmode tag is the solution
If you're willing to use SciPy:
>>> from scipy.stats import mode
>>> mode([1,2,3,1,2,1,1,1,3,2,2,1])
(array([ 1.]), array([ 6.]))
>>> most_frequent = mode([1,2,3,1,2,1,1,1,3,2,2,1])[0][0]
>>> most_frequent
1.0
Please be aware, this is a simplified explanation intended as a first step in seeking to understand this complex functionality.
May be helpful for visual learners who want to visualise what their project state looks like after each of these commands:
Given: - A - B - C (master)
For those who use Terminal with colour turned on (git config --global color.ui auto):
git reset --soft A
and you will see B and C's stuff in green (staged and ready to commit)
git reset --mixed A
(or git reset A
) and you will see B and C's stuff in red (unstaged and ready to be staged (green) and then committed)
git reset --hard A
and you will no longer see B and C's changes anywhere (will be as if they never existed)
Or for those who use a GUI program like 'Tower' or 'SourceTree'
git reset --soft A
and you will see B and C's stuff in the 'staged files' area ready to commit
git reset --mixed A
(or git reset A
) and you will see B and C's stuff in the 'unstaged files' area ready to be moved to staged and then committed
git reset --hard A
and you will no longer see B and C's changes anywhere (will be as if they never existed)
If you want to create model along with migration use this command:-
sequelize model:create --name regions --attributes name:string,status:boolean --underscored
--underscored it is used to create column having underscore like:- created_at,updated_at or any other column having underscore and support user defined columns having underscore.
Note that if you use Android Studio and download through its SDK Manager, the SDK is downloaded to ~/Library/Android/sdk
by default, not ~/.android-sdk-macosx
.
I would rather add this as a comment to @brismuth's excellent answer, but it seems I don't have enough reputation points yet.
$("#select_all").change(function () {
$('input[type="checkbox"]').prop("checked", $(this).prop("checked"));
});
What is wrong with using string.Length?
// len will be 5
int len = "Hello".Length;
I've used this (or very similar) code to add several TextViews to a LinearLayout:
// Quick & dirty pre-made list of text labels...
String names[] = {"alpha", "beta", "gamma", "delta", "epsilon"};
int namesLength = 5;
// Create a LayoutParams...
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.FILL_PARENT);
// Get existing UI containers...
LinearLayout nameButtons = (LinearLayout) view.findViewById(R.id.name_buttons);
TextView label = (TextView) view.findViewById(R.id.master_label);
TextView tv;
for (int i = 0; i < namesLength; i++) {
// Grab the name for this "button"
final String name = names[i];
tv = new TextView(context);
tv.setText(name);
// TextViews CAN have OnClickListeners
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
label.setText("Clicked button for " + name);
}
});
nameButtons.addView(tv, params);
}
The main difference between this and dicklaw795's code is it doesn't set() and re-get() the ID for each TextView--I found it unnecessary, although I may need it to later identify each button in a common handler routine (e.g. one called by onClick() for each TextView).
If you are searching literally the way to return a JSON list in flask and you are completly sure that your variable is a list then the easy way is (where bin is a list of 1's and 0's):
return jsonify({'ans':bin}), 201
Finally, in your client you will obtain something like
{ "ans": [ 0.0, 0.0, 1.0, 1.0, 0.0 ] }
There is a very good answer to the same question.
Adding following lines to "~/.gitconfig":
[alias]
lg1 = log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n'' %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
lg = !"git lg1"
If you want an efficient search that is often repeated, first sort the array (Array.Sort
) and then use Array.BinarySearch
.
Changing your lists to numpy
arrays will do the job!!
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15
plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()
Here is a simple example of converting your List into Spark RDD and then converting that Spark RDD into Dataframe.
Please note that I have used Spark-shell's scala REPL to execute following code, Here sc is an instance of SparkContext which is implicitly available in Spark-shell. Hope it answer your question.
scala> val numList = List(1,2,3,4,5)
numList: List[Int] = List(1, 2, 3, 4, 5)
scala> val numRDD = sc.parallelize(numList)
numRDD: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[80] at parallelize at <console>:28
scala> val numDF = numRDD.toDF
numDF: org.apache.spark.sql.DataFrame = [_1: int]
scala> numDF.show
+---+
| _1|
+---+
| 1|
| 2|
| 3|
| 4|
| 5|
+---+
<span class="btn-pTool">
<a class="btn-pToolName" href="#"></a>
</span>
That's empty. Try adding a non breaking space to give the link and span some contents:
<span class="btn-pTool">
<a class="btn-pToolName" href="#"> </a>
</span>
It's also worth noting that the CSS spec says that you can't give a span a background image because spans are not block elements. Put the background image code in the div's class style, or use <p> instead of <span>
. Some browsers might let you put a background in a span, but not all will (perhaps older versions of IE).
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
FXCop typically prefers OrdinalIgnoreCase
. But your requirements may vary.
For English there is very little difference. It is when you wander into languages that have different written language constructs that this becomes an issue. I am not experienced enough to give you more than that.
OrdinalIgnoreCase
The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames. http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx
InvariantCultureIgnoreCase
The StringComparer returned by the InvariantCultureIgnoreCase property compares strings in a linguistically relevant manner that ignores case, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures. http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx
The invariant culture is the CultureInfo object returned by the InvariantCulture property.
The InvariantCultureIgnoreCase property actually returns an instance of an anonymous class derived from the StringComparer class.
$form->getErrors() works for me.
This looks like valid Python code, so if the file is on your project's classpath (and not in some other directory or in arbitrary places) one way would be just to rename the file to "abc.py" and import it as a module, using import abc
. You can even update the values using the reload
function later. Then access the values as abc.path1
etc.
Of course, this can be dangerous in case the file contains other code that will be executed. I would not use it in any real, professional project, but for a small script or in interactive mode this seems to be the simplest solution.
Just put the abc.py
into the same directory as your script, or the directory where you open the interactive shell, and do import abc
or from abc import *
.
I have the same today on Win7.x64, this solve it.
Right Click MyComputer > Manage > Local Users and Groups > Groups > Administrators double click > your name should be there, if not press add...
To add on Tzot's and gns answers, here's an alternative way of copying files and folders recursively. (Python 3.X)
import os, shutil
root_src_dir = r'C:\MyMusic' #Path/Location of the source directory
root_dst_dir = 'D:MusicBackUp' #Path to the destination folder
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.copy(src_file, dst_dir)
Should it be your first time and you have no idea how to copy files and folders recursively, I hope this helps.
I recently came across this site: https://adoptopenjdk.net/
Seems reliable to me. Haven't tried myself but surely will give it a try.
License:
License(s) Build scripts and other code to produce the binaries, the website and other build infrastructure are licensed under Apache License, Version 2.0. OpenJDK code itself is licensed under GPL v2 with Classpath Exception.
EDIT: I was also delighted to learn that AdoptOpenJDK MSI installer (JDK and JRE) now comes with IcedTeaWeb, which is a replacement for Oracle WebStart - simple installer with almost 'next-next-next-finish' and the JWS applications works like they used to.
Define a class to store your data first
public class YourDataClass {
private String messageType;
private Timestamp timestamp;
private int count;
private int version;
// your get/setters
...........
}
And then initialize your map:
Map<Integer, YourDataClass> map = new HashMap<Integer, YourDataClass>();
AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() );
AB.insert( AB.end(), B.begin(), B.end() );
It's not good to keep changing the gulp & npm versions in-order to fix the errors. I was getting several exceptions last days after reinstall my working machine. And wasted tons of minutes to re-install & fixing those.
So, I decided to upgrade all to latest versions:
npm -v : v12.13.0
node -v : 6.13.0
gulp -v : CLI version: 2.2.0 Local version: 4.0.2
This error is getting because of the how it has coded in you gulpfile but not the version mismatch. So, Here you have to change 2 things in the gulpfile to aligned with Gulp version 4. Gulp 4 has changed how initiate the task than Version 3.
gulp.task('serve', ['sass'], function() {..});
But in V4 it should be like:
function serve() {
...
}
gulp.task('serve', gulp.series(sass));
gulp.task('serve', ['sass'], function() { ... });
But in V4, it should be:
gulp.task('serve', gulp.series(sass));
An example of how to implement it:
public bool ValidateSocialSecNumber(string socialSecNumber)
{
//Accepts only 10 digits, no more no less. (Like Mike's answer)
Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)");
if(pattern.isMatch(socialSecNumber))
{
//Do something
return true;
}
else
{
return false;
}
}
You could've also done it in another way by e.g. using Match
and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
I use this method to start an Intent from RecyclerView:
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
final MyClass myClass = mList.get(i);
viewHolder.txtViewTitle.setText(myclass.name);
...
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
Intent detailIntent = new Intent(mContext, type.class);
detailIntent.putExtra("MyClass", myclass);
mContext.startActivity(detailIntent);
}
}
);
For gradle
compile('org.xxx:xxx:1.0-SNAPSHOT'){
exclude module: 'log4j'
exclude module: 'slf4j-log4j12'
}
innerHTML
is a string representing the contents of the element.
You want to modify the element itself. Drop the .innerHTML
part.
If the string was constructed in the same program, I would recommend using this:
String newline = System.getProperty("line.separator");
boolean hasNewline = word.contains(newline);
But if you are specced to use \n, this driver illustrates what to do:
class NewLineTest {
public static void main(String[] args) {
String hasNewline = "this has a newline\n.";
String noNewline = "this doesn't";
System.out.println(hasNewline.contains("\n"));
System.out.println(hasNewline.contains("\\n"));
System.out.println(noNewline.contains("\n"));
System.out.println(noNewline.contains("\\n"));
}
}
Resulted in
true
false
false
false
In reponse to your comment:
class NewLineTest {
public static void main(String[] args) {
String word = "test\n.";
System.out.println(word.length());
System.out.println(word);
word = word.replace("\n","\n ");
System.out.println(word.length());
System.out.println(word);
}
}
Results in
6
test
.
7
test
.
Yes, constructors are allowed to throw exceptions.
However, be very wise in choosing what exceptions they should be - checked exceptions or unchecked. Unchecked exceptions are basically subclasses of RuntimeException.
In almost all cases (I could not come up with an exception to this case), you'll need to throw a checked exception. The reason being that unchecked exceptions (like NullPointerException) are normally due to programming errors (like not validating inputs sufficiently).
The advantage that a checked exception offers is that the programmer is forced to catch the exception in his instantiation code, and thereby realizes that there can be a failure to create the object instance. Of course, only a code review will catch the poor programming practice of swallowing an exception.
In Java (version 6+), you can also do:
Desktop d = Desktop.getDesktop();
d.browse(uri);
Though this won't work on all Linuxes. At the time of writing, Gnome is supported, KDE isn't.
I find it easiest (and most readable) to just copy the line and comment out the original version:
#Old version of ls:
#ls -l $([ ] && -F is turned off) -a /etc
ls -l -a /etc
worked in my case
var arr2 = _.filter(arr, function(item){
if ( item == 3 ) return item;
});
May I suggest trying to use in else if statement in your if/else statement. And if you don't want to run any code that not under any conditions you want you can just leave the else out at the end of the statement. else if can also be used for any number of diversion paths that need things to be a certain condition for each.
if(condition 1){
} else if (condition 2) {
}else {
}
I have successfully achieved this with the below code. Put the below code in an SQL Server new query window and try:
CREATE TABLE tempDBTableDetails ( TableName VARCHAR(500), [RowCount] VARCHAR(500), TotalSpaceKB VARCHAR(500),
UsedSpaceKB VARCHAR(500), UnusedSpaceKB VARCHAR(500) )
-- STEP 1 ::
DECLARE @cmd VARCHAR(4000)
INSERT INTO tempDBTableDetails
SELECT 'TableName', 'RowCount', 'TotalSpaceKB', 'UsedSpaceKB', 'UnusedSpaceKB'
INSERT INTO tempDBTableDetails
SELECT
S.name +'.'+ T.name as TableName,
Convert(varchar,Cast(SUM(P.rows) as Money),1) as [RowCount],
Convert(varchar,Cast(SUM(a.total_pages) * 8 as Money),1) AS TotalSpaceKB,
Convert(varchar,Cast(SUM(a.used_pages) * 8 as Money),1) AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM sys.tables T
INNER JOIN sys.partitions P ON P.OBJECT_ID = T.OBJECT_ID
INNER JOIN sys.schemas S ON T.schema_id = S.schema_id
INNER JOIN sys.allocation_units A ON p.partition_id = a.container_id
WHERE T.is_ms_shipped = 0 AND P.index_id IN (1,0)
GROUP BY S.name, T.name
ORDER BY SUM(P.rows) DESC
-- SELECT * FROM [FIINFRA-DB-SIT].dbo.tempDBTableDetails ORDER BY LEN([RowCount]) DESC
SET @cmd = 'bcp "SELECT * FROM [FIINFRA-DB-SIT].dbo.tempDBTableDetails ORDER BY LEN([RowCount]) DESC" queryout "D:\Milind\export.xls" -U sa -P dbowner -c'
Exec xp_cmdshell @cmd
--DECLARE @HeaderCmd VARCHAR(4000)
--SET @HeaderCmd = 'SELECT ''TableName'', ''RowCount'', ''TotalSpaceKB'', ''UsedSpaceKB'', ''UnusedSpaceKB'''
exec master..xp_cmdshell 'BCP "SELECT ''TableName'', ''RowCount'', ''TotalSpaceKB'', ''UsedSpaceKB'', ''UnusedSpaceKB''" queryout "d:\milind\header.xls" -U sa -P dbowner -c'
exec master..xp_cmdshell 'copy /b "d:\Milind\header.xls"+"d:\Milind\export.xls" "d:/Milind/result.xls"'
exec master..xp_cmdshell 'del "d:\Milind\header.xls"'
exec master..xp_cmdshell 'del "d:\Milind\export.xls"'
DROP TABLE tempDBTableDetails
I would use DBA_SOURCE (if you have access to it) because if the object you require is not owned by the schema under which you are logged in you will not see it.
If you need to know the functions and Procs inside the packages try something like this:
select * from all_source
where type = 'PACKAGE'
and (upper(text) like '%FUNCTION%' or upper(text) like '%PROCEDURE%')
and owner != 'SYS';
The last line prevents all the sys stuff (DBMS_ et al) from being returned. This will work in user_source if you just want your own schema stuff.
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
Look for "poi-3.17.jar"!!!
Problem solved and errors disappeared.
All the answers here are wrong, they missing important piece, the height
.container{
width:200px;
height:600px;
background:red
}
.title {
overflow: hidden;
line-height: 20px;
height: 40px;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
<div class="container">
<div class="title">this is a long text you cant cut it in half</div>
</div>
Is JSTL's join()
, what you searched for?
<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />
It appears that it's a bug in the Facebook app that was reported in April 2011 and has still yet to be fixed by the Android Facebook developers.
The only work around for the moment is to use their SDK.
There are few steps to upgrade 2/4/5 to Angular 6.
npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
npm install
To fix the issue related to "angular.json" :-
ng update @angular/cli --migrate-only --from=1.7.4
Store MIGRATION
https://github.com/ngrx/platform/blob/master/MIGRATION.md#ngrxstore
RXJS MIGRATION
https://www.academind.com/learn/javascript/rxjs-6-what-changed/
Hoping this will help you :)
This will list all jpg
files in the folder you define under url: and append them to a div
as a paragraph. Can do it with ul li
as well.
$.ajax({
url: "YOUR FOLDER",
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
// will loop through
var images = $(this).attr("href");
$('<p></p>').html(images).appendTo('a div of your choice')
});
}
});