You can use the contains selector to search for elements containing a specific text
var elem = $('div.text_div:contains("This div contains some text")')?;
elem.text(elem.text().replace("contains", "Hello everyone"));
??????????????????????????????????????????
This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019
Directly assign the Height & Width values for a view:
userView.frame.size.height = 0
userView.frame.size.width = 10
Assign the CGRect for the Frame
userView.frame = CGRect(x:0, y: 0, width:0, height:0)
Method Details:
CGRect(x: point of X, y: point of Y, width: Width of View, height: Height of View)
Using an Extension method for CGRECT
Add following extension code in any swift file,
extension CGRect {
init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {
self.init(x:x, y:y, width:w, height:h)
}
}
Use the following code anywhere in your application for the view to set the size parameters
userView.frame = CGRect(1, 1, 20, 45)
This does cause "funky characters":
System.out.println( "Mr. Foo".trim().replace('.','\0'));
produces:
Mr[] Foo
in my Eclipse console, where the [] is shown as a square box. As others have posted, use String.replace()
.
I realized it was a port issue since I was running IIS and other web servers in my machine. But I was more interested to see a detailed error message with the port number in the UI.
Seems like it was not logged in the UI or log file (at least in my case), but in the Event viewer (Control panel -> View Event Logs). Under the Even viewer -> Windows Logs -> Application
I could see a permission error something like the below one:
An attempt was made to access a socket in a way forbidden by its access permissions. : AH00072: make_sock: could not bind to address 0.0.0.0:443
To fix this permission issue for SSL port, Please change the below line in httpd-ssl.conf (C:\xampp\apache\conf\extra)
# When we also provide SSL we have to listen to the
standard HTTP port (see above) and to the HTTPS port
Listen xxx
Replace XXX with any valid port number that is open in your machine
If you are having issues with Port 80, then change the httpd.conf file (C:\xampp\apache\conf)
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 127.0.0.1:8000
I have also summarized other solutions that I came across:
Write editTextBackground.xml in drawable folder in resources
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="@color/borderColor" />
</shape>
don't forget to declare color in resources named borderColor
.
and assign this background to the EditText
in xml background attribute
<EditText
android:id="@+id/text"
android:background="@drawable/editTextBackground"
/>
and it'll set border to EditText
.
You can change border of edit text without drawable by using style
attribute
style="@style/Widget.AppCompat.EditText"
for more details visit customize edit text
It is a new signing mechanism introduced in Android 7.0, with additional features designed to make the APK signature more secure.
It is not mandatory. You should check BOTH of those checkboxes if possible, but if the new V2 signing mechanism gives you problems, you can omit it.
So you can just leave V2 unchecked if you encounter problems, but should have it checked if possible.
UPDATED: This is now mandatory when targeting Android 11.
In my case, i was using ContainerViewController and putting UITableViewController in it. After removing ContainerViewController. Issues goes away.
Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length
returns undefined rather than 5.
This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.
// TypeScript
const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);
// Explicitly convert Date to Number
const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );
The range
function wil give you a list of numbers, while the for
loop will iterate through the list and execute the given code for each of its items.
for i in range(5):
print i
This simply executes print i
five times, for i ranging from 0 to 4.
for i in range(5):
a=i+1
This will execute a=i+1
five times. Since you are overwriting the value of a
on each iteration, at the end you will only get the value for the last iteration, that is 4+1.
Useful links:
http://www.network-theory.co.uk/docs/pytut/rangeFunction.html
http://www.ibiblio.org/swaroopch/byteofpython/read/for-loop.html
Thanks for this question, actually I am looking for something else which is in below query. this may helps someone.
SELECT DISTINCT CASE WHEN OPPORTUNITY='' THEN '(BLANK)' ELSE OPPORTUNITY END
AS OPP,LEN(OPPORTUNITY) FROM [DBO].[TBL]
above query is to fill in dropdown which blank values shows as "(blank)". Also if we pass this value into sql where clause to get blank values with other values I don't know how to handle that. And finally came up with below solution this may helps to somebody.
here it is ,
DECLARE @OPP TABLE (OPP VARCHAR(100))
INSERT INTO @OPP VALUES('(BLANK)'),('UNFUNDED'),('FUNDED/NOT COMMITTED')
SELECT DISTINCT [OPPORTUNITY]
FROM [DBO].[TBL] WHERE ( CASE WHEN OPPORTUNITY ='' THEN '(BLANK)' ELSE OPPORTUNITY END IN (SELECT OPP FROM @OPP))
ORDER BY 1
Create Dynamic angular variables from results
angular.forEach(results, function (value, key) {
if (key != null) {
$parse(key).assign($scope, value);
}
});
ps. don't forget to pass in the $parse attribute into your controller's function
The apiKey in this configuration snippet just identifies your Firebase project on the Google servers. It is not a security risk for someone to know it. In fact, it is necessary for them to know it, in order for them to interact with your Firebase project. This same configuration data is also included in every iOS and Android app that uses Firebase as its backend.
In that sense it is very similar to the database URL that identifies the back-end database associated with your project in the same snippet: https://<app-id>.firebaseio.com
. See this question on why this is not a security risk: How to restrict Firebase data modification?, including the use of Firebase's server side security rules to ensure only authorized users can access the backend services.
If you want to learn how to secure all data access to your Firebase backend services is authorized, read up on the documentation on Firebase security rules. These rules control access to file storage and database access, and are enforced on the Firebase servers. So no matter if it's your code, or somebody else's code that uses you configuration data, it can only do what the security rules allow it to do.
For another explanation of what Firebase uses these values for, and for which of them you can set quotas, see the Firebase documentation on using and managing API keys.
If you'd like to reduce the risk of committing this configuration data to version control, consider using the SDK auto-configuration of Firebase Hosting. While the keys will still end up in the browser in the same format, they won't be hard-coded into your code anymore with that.
this helped me to fix current issue
If you're using macOS Sierra 10.12.2 or later, you will need to modify your ~/.ssh/config file to automatically load keys into the ssh-agent and store passphrases in your keychain.
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa
The following code is less complex and gives the same result. Note that 'X' is the number of seconds to be converted to hours.
In Oracle use:
SELECT TO_CHAR (TRUNC (SYSDATE) + NUMTODSINTERVAL (X, 'second'),
'hh24:mi:ss'
) hr
FROM DUAL;
In SqlServer use:
SELECT CONVERT(varchar, DATEADD(s, X, 0), 108);
The suggested method for communicating between fragments is to use callbacks\listeners that are managed by your main Activity.
I think the code on this page is pretty clear: http://developer.android.com/training/basics/fragments/communicating.html
You can also reference the IO 2012 Schedule app, which is designed to be a de-facto reference app. It can be found here: http://code.google.com/p/iosched/
Also, here is a SO question with good info: How to pass data between fragments
this works....
<script language="javascript">
(function($) {
$.fn.MessageBox = function(msg) {
return this.each(function(){
alert(msg);
})
};
})(jQuery);?
</script>
.
<body>
<div class="Title">Welcome!</div>
<input type="button" value="ahaha" onclick="$(this).MessageBox('msg');" />
</body>
edit
you are using a failsafe jQuery code using the $ alias... it should be written like:
(function($) {
// plugin code here, use $ as much as you like
})(jQuery);
or
jQuery(function($) {
// your code using $ alias here
});
note that it has a 'jQuery' word in each of it....
Your thread's locale is set to one in which the decimal mark is "," instead of ".".
Try using this:
float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);
Note, however, that a float cannot hold that many digits of precision. You would have to use double or Decimal to do so.
Do you want to this code?
public static enum FieldIndex {
HDB_TRX_ID, //TRX ID
HDB_SYS_ID //SYSTEM ID
}
public String print(ArrayList<String> itemName){
return itemName.get(FieldIndex.HDB_TRX_ID.ordinal());
}
<nav>
<a href="#section1">1</a>
<a href="#section2">2</a>
<a href="#section3">3</a>
</nav>
<section id="section1">1</section>
<section id="section2" class="fifty">2</section>
<section id="section3">3</section>
<style>
* {padding: 0; margin: 0;}
nav {
background: black;
position: fixed;
}
a {
color: #fff;
display: inline-block;
padding: 0 1em;
height: 50px;
}
section {
background: red;
height: 100vh;
text-align: center;
font-size: 5em;
}
html {
scroll-behavior: smooth;
}
#section1{
background-color:green;
}
#section3{
background-color:yellow;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" >
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
</script>
_x000D_
Extending @Ryogi answer above, you can take advantage of the lower.tail
parameter like so:
qt(0.25/2, 40, lower.tail = FALSE)
# 75% confidence
qt(0.01/2, 40, lower.tail = FALSE)
# 99% confidence
I've written a stored procedure to show how to do this before. You basically have to process the string. I tried to post the code here but the formatting got all screwy.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[uspSplitTextList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[uspSplitTextList]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
-- uspSplitTextList
--
-- Description:
-- splits a separated list of text items and returns the text items
--
-- Arguments:
-- @list_text - list of text items
-- @Delimiter - delimiter
--
-- Notes:
-- 02/22/2006 - WSR : use DATALENGTH instead of LEN throughout because LEN doesn't count trailing blanks
--
-- History:
-- 02/22/2006 - WSR : revised algorithm to account for items crossing 8000 character boundary
-- 09/18/2006 - WSR : added to this project
--
CREATE PROCEDURE uspSplitTextList
@list_text text,
@Delimiter varchar(3)
AS
SET NOCOUNT ON
DECLARE @InputLen integer -- input text length
DECLARE @TextPos integer -- current position within input text
DECLARE @Chunk varchar(8000) -- chunk within input text
DECLARE @ChunkPos integer -- current position within chunk
DECLARE @DelimPos integer -- position of delimiter
DECLARE @ChunkLen integer -- chunk length
DECLARE @DelimLen integer -- delimiter length
DECLARE @ItemBegPos integer -- item starting position in text
DECLARE @ItemOrder integer -- item order in list
DECLARE @DelimChar varchar(1) -- first character of delimiter (simple delimiter)
-- create table to hold list items
-- actually their positions because we may want to scrub this list eliminating bad entries before substring is applied
CREATE TABLE #list_items ( item_order integer, item_begpos integer, item_endpos integer )
-- process list
IF @list_text IS NOT NULL
BEGIN
-- initialize
SET @InputLen = DATALENGTH(@list_text)
SET @TextPos = 1
SET @DelimChar = SUBSTRING(@Delimiter, 1, 1)
SET @DelimLen = DATALENGTH(@Delimiter)
SET @ItemBegPos = 1
SET @ItemOrder = 1
SET @ChunkLen = 1
-- cycle through input processing chunks
WHILE @TextPos <= @InputLen AND @ChunkLen <> 0
BEGIN
-- get current chunk
SET @Chunk = SUBSTRING(@list_text, @TextPos, 8000)
-- setup initial variable values
SET @ChunkPos = 1
SET @ChunkLen = DATALENGTH(@Chunk)
SET @DelimPos = CHARINDEX(@DelimChar, @Chunk, @ChunkPos)
-- loop over the chunk, until the last delimiter
WHILE @ChunkPos <= @ChunkLen AND @DelimPos <> 0
BEGIN
-- see if this is a full delimiter
IF SUBSTRING(@list_text, (@TextPos + @DelimPos - 1), @DelimLen) = @Delimiter
BEGIN
-- insert position
INSERT INTO #list_items (item_order, item_begpos, item_endpos)
VALUES (@ItemOrder, @ItemBegPos, (@TextPos + @DelimPos - 1) - 1)
-- adjust positions
SET @ItemOrder = @ItemOrder + 1
SET @ItemBegPos = (@TextPos + @DelimPos - 1) + @DelimLen
SET @ChunkPos = @DelimPos + @DelimLen
END
ELSE
BEGIN
-- adjust positions
SET @ChunkPos = @DelimPos + 1
END
-- find next delimiter
SET @DelimPos = CHARINDEX(@DelimChar, @Chunk, @ChunkPos)
END
-- adjust positions
SET @TextPos = @TextPos + @ChunkLen
END
-- handle last item
IF @ItemBegPos <= @InputLen
BEGIN
-- insert position
INSERT INTO #list_items (item_order, item_begpos, item_endpos)
VALUES (@ItemOrder, @ItemBegPos, @InputLen)
END
-- delete the bad items
DELETE FROM #list_items
WHERE item_endpos < item_begpos
-- return list items
SELECT SUBSTRING(@list_text, item_begpos, (item_endpos - item_begpos + 1)) AS item_text, item_order, item_begpos, item_endpos
FROM #list_items
ORDER BY item_order
END
DROP TABLE #list_items
RETURN
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
I don't know if this is good enough but I made a static ThreadHelperClass class and implemented it as following .Now I can easily set text property of various controls without much coding .
public static class ThreadHelperClass
{
delegate void SetTextCallback(Form f, Control ctrl, string text);
/// <summary>
/// Set text property of various controls
/// </summary>
/// <param name="form">The calling form</param>
/// <param name="ctrl"></param>
/// <param name="text"></param>
public static void SetText(Form form, Control ctrl, string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (ctrl.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
form.Invoke(d, new object[] { form, ctrl, text });
}
else
{
ctrl.Text = text;
}
}
}
Using the code:
private void btnTestThread_Click(object sender, EventArgs e)
{
Thread demoThread =
new Thread(new ThreadStart(this.ThreadProcSafe));
demoThread.Start();
}
// This method is executed on the worker thread and makes
// a thread-safe call on the TextBox control.
private void ThreadProcSafe()
{
ThreadHelperClass.SetText(this, textBox1, "This text was set safely.");
ThreadHelperClass.SetText(this, textBox2, "another text was set safely.");
}
There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:
.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt
And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:
@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit
Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:
@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server
For specific versions, such as mysql-server-5.6
, you'll need to specify the version in like this:
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6
For mysql-community-server, the keys are slightly different:
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server
Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)
If your shell doesn't support here-strings (zsh, ksh93 and bash support them), use:
echo ... | sudo debconf-set-selections
You might want also to have a look at jmx4perl. It provides java-less access to a remote Java EE Server's MBeans. However, a small agent servlet needs to be installed on the target platform, which provides a restful JMX Access via HTTP with a JSON payload. (Version 0.50 will add an agentless mode by implementing a JSR-160 proxy).
Advantages are quick startup times compared to launching a local java JVM and ease of use. jmx4perl comes with a full set of Perl modules which can be easily used in your own scripts:
use JMX::Jmx4Perl;
use JMX::Jmx4Perl::Alias; # Import certains aliases for MBeans
print "Memory Used: ",
JMX::Jmx4Perl
->new(url => "http://localhost:8080/j4p")
->get_attribute(MEMORY_HEAP_USED);
You can also use alias for common MBean/Attribute/Operation combos (e.g. for most MXBeans). For additional features (Nagios-Plugin, XPath-like access to complex attribute types, ...), please refer to the documentation of jmx4perl.
I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:
select Detail.ReceiptDate AS 'DATE',
SUM(TotalMailed),
SUM(TotalReturnMail),
SUM(TraceReturnedMail)
from
(
select SentDate AS 'ReceiptDate',
count('TotalMailed') AS TotalMailed,
0 as TotalReturnMail,
0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate
UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate',
0 AS TotalMailed,
count(TotalReturnMail) as TotalReturnMail,
0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY MDE.ReturnMailDate
UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate',
0 AS TotalMailed,
0 as TotalReturnMail,
count(TraceReturnedMail) as TraceReturnedMail
from MailDataExtract MDE
inner join DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate
) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1
I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).
Also in Logic Friday the expression A | B
just returns 3 entries in truth table; I expected 4.
if you are using matplotlib version 3.1.1 or above, you can try:
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
x = [1, 3, 4, 6, 7, 9]
y = [0, 0, 5, 8, 8, 8]
classes = ['A', 'B', 'C']
values = [0, 0, 1, 2, 2, 2]
colours = ListedColormap(['r','b','g'])
scatter = plt.scatter(x, y,c=values, cmap=colours)
plt.legend(handles=scatter.legend_elements()[0], labels=classes)
This is going to be largely dependent on the RDBMS you're using, and whether a .NET option even exists for that RDBMS.
If you're using SQL Server, use the SqlBulkCopy class.
For other database vendors, try googling for them specifically. For example a search for ".NET Bulk insert into Oracle" turned up some interesting results, including this link back to Stack Overflow: Bulk Insert to Oracle using .NET.
I had the same problem, pillow was installed with an environment.yml in anaconda
I am quickly learning that pip and setuptools must always be up to date or I will have problems. Always update these tools before installing packages.For any package import problem uninstall the package upgrade the listed tools(maybe even your base environment) and reinstall.
conda uninstall pillow
python -m pip install pip --upgrade
pip install setuptools --upgrade
pip install pillow
If using Anaconda, from the base environment first run the following before installing packages/environments:
conda update conda
Updating the base env is not required to fix this issue but is a good practice to avoid similar problems
@theeastcoastwest touched on the pip upgrade in their answer but I felt more information was needed
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
i would recommend using this:
background-repeat:no-repeat;
background-image: url(your file location here);
background-size:cover;(will only work with css3)
hope it helps :D
And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.
Note that for this to work, you also need to set the dragDropEffect within _drawEnter...
private void Form1_DragEnter(object sender, DragEventArgs e)
{
Console.WriteLine("DragEnter!");
e.Effect = DragDropEffects.Copy;
}
Source: Drag and Drop not working in C# Winforms Application
try this,
df.loc[df['eri_white']==1,'race_label'] = 'White'
df.loc[df['eri_hawaiian']==1,'race_label'] = 'Haw/Pac Isl.'
df.loc[df['eri_afr_amer']==1,'race_label'] = 'Black/AA'
df.loc[df['eri_asian']==1,'race_label'] = 'Asian'
df.loc[df['eri_nat_amer']==1,'race_label'] = 'A/I AK Native'
df.loc[(df['eri_afr_amer'] + df['eri_asian'] + df['eri_hawaiian'] + df['eri_nat_amer'] + df['eri_white']) > 1,'race_label'] = 'Two Or More'
df.loc[df['eri_hispanic']==1,'race_label'] = 'Hispanic'
df['race_label'].fillna('Other', inplace=True)
O/P:
lname fname rno_cd eri_afr_amer eri_asian eri_hawaiian \
0 MOST JEFF E 0 0 0
1 CRUISE TOM E 0 0 0
2 DEPP JOHNNY NaN 0 0 0
3 DICAP LEO NaN 0 0 0
4 BRANDO MARLON E 0 0 0
5 HANKS TOM NaN 0 0 0
6 DENIRO ROBERT E 0 1 0
7 PACINO AL E 0 0 0
8 WILLIAMS ROBIN E 0 0 1
9 EASTWOOD CLINT E 0 0 0
eri_hispanic eri_nat_amer eri_white rno_defined race_label
0 0 0 1 White White
1 1 0 0 White Hispanic
2 0 0 1 Unknown White
3 0 0 1 Unknown White
4 0 0 0 White Other
5 0 0 1 Unknown White
6 0 0 1 White Two Or More
7 0 0 1 White White
8 0 0 0 White Haw/Pac Isl.
9 0 0 1 White White
use .loc
instead of apply
.
it improves vectorization.
.loc
works in simple manner, mask rows based on the condition, apply values to the freeze rows.
for more details visit, .loc docs
Performance metrics:
Accepted Answer:
def label_race (row):
if row['eri_hispanic'] == 1 :
return 'Hispanic'
if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
return 'Two Or More'
if row['eri_nat_amer'] == 1 :
return 'A/I AK Native'
if row['eri_asian'] == 1:
return 'Asian'
if row['eri_afr_amer'] == 1:
return 'Black/AA'
if row['eri_hawaiian'] == 1:
return 'Haw/Pac Isl.'
if row['eri_white'] == 1:
return 'White'
return 'Other'
df=pd.read_csv('dataser.csv')
df = pd.concat([df]*1000)
%timeit df.apply(lambda row: label_race(row), axis=1)
1.15 s ± 46.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
My Proposed Answer:
def label_race(df):
df.loc[df['eri_white']==1,'race_label'] = 'White'
df.loc[df['eri_hawaiian']==1,'race_label'] = 'Haw/Pac Isl.'
df.loc[df['eri_afr_amer']==1,'race_label'] = 'Black/AA'
df.loc[df['eri_asian']==1,'race_label'] = 'Asian'
df.loc[df['eri_nat_amer']==1,'race_label'] = 'A/I AK Native'
df.loc[(df['eri_afr_amer'] + df['eri_asian'] + df['eri_hawaiian'] + df['eri_nat_amer'] + df['eri_white']) > 1,'race_label'] = 'Two Or More'
df.loc[df['eri_hispanic']==1,'race_label'] = 'Hispanic'
df['race_label'].fillna('Other', inplace=True)
df=pd.read_csv('s22.csv')
df = pd.concat([df]*1000)
%timeit label_race(df)
24.7 ms ± 1.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
(repost from my other response)
Use cli utility keytool from java software distribution for import (and trust!) needed certificates
Sample:
From cli change dir to jre\bin
Check keystore (file found in jre\bin directory)
keytool -list -keystore ..\lib\security\cacerts
Password is changeit
Download and save all certificates in chain from needed server.
Add certificates (before need to remove "read-only" attribute on file ..\lib\security\cacerts
), run:
keytool -alias REPLACE_TO_ANY_UNIQ_NAME -import -keystore.\lib\security\cacerts -file "r:\root.crt"
accidentally I found such a simple tip. Other solutions require the use of InstallCert.Java and JDK
source: http://www.java-samples.com/showtutorial.php?tutorialid=210
In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details
BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)
Means you should use like this :
Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)
So, it worked in MVC 4
@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
new { @id = "signupform" }))
{
<input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
<input type="submit" value="Create" id="btnSubmit" />
}
The simplest way to get the html
element natively is:
document.documentElement
Here's the reference: https://developer.mozilla.org/en-US/docs/Web/API/Document.documentElement.
UPDATE: To then grab the html
element as a string you would do:
document.documentElement.outerHTML
As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.
For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.
$person = "Rasmus Lerdorf";
$found = false;
foreach($organization as $oKey=>$department)
{
foreach($department as $dKey=>$group)
{
foreach($group as $gKey=>$employee)
{
if ($employee['fullname'] == $person)
{
$found = true;
break 3;
}
} // group
} // department
} // organization
Using a context manager as Paul Price sugggested
import numpy as np
class fullprint:
'context manager for printing full numpy arrays'
def __init__(self, **kwargs):
kwargs.setdefault('threshold', np.inf)
self.opt = kwargs
def __enter__(self):
self._opt = np.get_printoptions()
np.set_printoptions(**self.opt)
def __exit__(self, type, value, traceback):
np.set_printoptions(**self._opt)
if __name__ == '__main__':
a = np.arange(1001)
with fullprint():
print(a)
print(a)
with fullprint(threshold=None, edgeitems=10):
print(a)
The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.
(And enhancing print statements with Data::Dumper)
This guide says:
6.1.5 Sending JDBC NULL as an IN parameter
The setNull method allows a programmer to send a JDBC NULL (a generic SQL NULL) value to the database as an IN parameter. Note, however, that one must still specify the JDBC type of the parameter.
A JDBC NULL will also be sent to the database when a Java null value is passed to a setXXX method (if it takes Java objects as arguments). The method setObject, however, can take a null value only if the JDBC type is specified.
So yes they're equivalent.
Now this become even simpler and more flexible by using CSS GRID.You just have to overlap the blured background(imgbg) with the text(h2)
<div class="container">
<div class="imgbg"></div>
<h2>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Facilis enim
aut rerum mollitia quas voluptas delectus facere magni cum unde?:)
</h2>
</div>
and the css:
.container {
display: grid;
width: 30em;
}
.imgbg {
background: url(bg3.jpg) no-repeat center;
background-size: cover;
grid-column: 1/-1;
grid-row: 1/-1;
filter: blur(4px);
}
.container h2 {
text-transform: uppercase;
grid-column: 1/-1;
grid-row: 1/-1;
z-index: 2;
}
to print first two letter of a string
str = "string"
print(str[0:2])
I have just the same problem. I have made a lot of renaming in my solution. After it I got two not working web-applications and several another web-applications were all right. I got error that I have wrong routes. When I have tried to setup break point in Application_Start
method, and then restart IIS, VS didn't break execution. With workable web-applications break was working. Then I have recalled that "clean solution" and "rebuild" doesn't delete assemblies that left after renaming. And that was solution! I have manually cleaned bin
directories of my buggy-web-applications and then saw new error in Global.asax
Inherits=""
attribute was referenced old dll. I have changed it on new and break began to work. Suppose that, during renaming Global.asax wasn't updated, and IIS took old assembly (with wrong routes) to start application.
First, Google created the "use less secure accounts method" function:
https://myaccount.google.com/security
Then created the another permission:
https://accounts.google.com/b/0/DisplayUnlockCaptcha
Hope it helps.
If the size of the array is known at compile time, you can use the structure size to determine the number of elements.
struct foo fooarr[10];
for(i = 0; i < sizeof(fooarr) / sizeof(struct foo); i++)
{
do_something(fooarr[i].data);
}
If it is not known at compile time, you will need to store a size somewhere or create a special terminator value at the end of the array.
Creating a property with only a getter makes your property read-only for any code that is outside the class.
You can however change the value using methods provided by your class :
public class FuelConsumption {
private double fuel;
public double Fuel
{
get { return this.fuel; }
}
public void FillFuelTank(double amount)
{
this.fuel += amount;
}
}
public static void Main()
{
FuelConsumption f = new FuelConsumption();
double a;
a = f.Fuel; // Will work
f.Fuel = a; // Does not compile
f.FillFuelTank(10); // Value is changed from the method's code
}
Setting the private field of your class as readonly
allows you to set the field value only once (using an inline assignment or in the class constructor).
You will not be able to change it later.
public class ReadOnlyFields {
private readonly double a = 2.0;
private readonly double b;
public ReadOnlyFields()
{
this.b = 4.0;
}
}
readonly
class fields are often used for variables that are initialized during class construction, and will never be changed later on.
In short, if you need to ensure your property value will never be changed from the outside, but you need to be able to change it from inside your class code, use a "Get-only" property.
If you need to store a value which will never change once its initial value has been set, use a readonly
field.
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.
I fixed it just by changing target compile version to 1.8. Its in:
File >> Settings >> Build, Execution, Deployment >> Compiler >> Java Compiler
Expanding on David's answer, I just add a simple class to augment Bootstrap like this:
.money, .number {
text-align: right !important;
}
var versionAttrib = new AssemblyName(Assembly.GetExecutingAssembly().FullName);
Best way is to use a function:
#include <map>
using namespace std;
map<int,int> create_map()
{
map<int,int> m;
m[1] = 2;
m[3] = 4;
m[5] = 6;
return m;
}
map<int,int> m = create_map();
A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.
Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.
def f0(a)
def f1(*a)
def f2(**a)
def f3(*a, **b)
etc...
System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting this static property to false:
System.Net.ServicePointManager.Expect100Continue = false;
Some servers choke on that header and send back the 417 error you're seeing.
Give that a shot.
Your file has syntax error, so your file was not interpreted, so settings was not changed and you have blank page.
You can separate your file to two.
index.php
<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
include 'error.php';
error.php
<?
echo('catch this -> ' ;. $thisdoesnotexist);
If you really gotta be fast (not that I believe you do):
char[] chars = sourceDate.toCharArray();
chars[10] = ' ';
String targetDate = new String(chars, 0, 19);
function parseVideo(url) {
// - Supported YouTube URL formats:
// - http://www.youtube.com/watch?v=My2FRPA3Gf8
// - http://youtu.be/My2FRPA3Gf8
// - https://youtube.googleapis.com/v/My2FRPA3Gf8
// - Supported Vimeo URL formats:
// - http://vimeo.com/25451551
// - http://player.vimeo.com/video/25451551
// - Also supports relative URLs:
// - //player.vimeo.com/video/25451551
url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);
if (RegExp.$3.indexOf('youtu') > -1) {
var type = 'youtube';
} else if (RegExp.$3.indexOf('vimeo') > -1) {
var type = 'vimeo';
}
return {
type: type,
id: RegExp.$6
};
}
function getVideoThumbnail(url, cb) {
var videoObj = parseVideo(url);
if (videoObj.type == 'youtube') {
cb('//img.youtube.com/vi/' + videoObj.id + '/maxresdefault.jpg');
} else if (videoObj.type == 'vimeo') {
$.get('http://vimeo.com/api/v2/video/' + videoObj.id + '.json', function(data) {
cb(data[0].thumbnail_large);
});
}
}
func post() {
NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"),
object: nil,
userInfo:["key0": "value", "key1": 1234])
}
func addObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(someMethod),
name: Notification.Name("SomeNotificationName"),
object: nil)
}
@objc func someMethod(_ notification: Notification) {
let info0 = notification.userInfo?["key0"]
let info1 = notification.userInfo?["key1"]
}
Replace Notification.Name("SomeNotificationName")
with .someNotificationName
:
extension Notification.Name {
static let someNotificationName = Notification.Name("SomeNotificationName")
}
Replace "key0"
and "key1"
with Notification.Key.key0
and Notification.Key.key1
:
extension Notification {
enum Key: String {
case key0
case key1
}
}
Why should I definitely do this ? To avoid costly typo errors, enjoy renaming, enjoy find usage etc...
Although they vary slightly as to how they retrieve a height value, i.e some would calculate the whole element including padding, margin, scrollbar, etc and others would just calculate the element in its raw form.
You can try these ones:
javascript:
var myDiv = document.getElementById("myDiv");
myDiv.clientHeight;
myDiv.scrollHeight;
myDiv.offsetHeight;
or in jquery:
$("#myDiv").height();
$("#myDiv").innerHeight();
$("#myDiv").outerHeight();
On a system with both Python 2 and 3 installed and with pip2
-installed Pillow failing to provide Image
, it is possible to install PIL for Python 2 in a way that will solve ImportError: No module named Image
:
easy_install-2.7 --user PIL
or
sudo easy_install-2.7 PIL
I would opt for NOT EXISTS
in this case.
SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
(SELECT 'X'
FROM Domain2 D2
WHERE D2.ShortCode = D1.ShortCode
)
- (void)GetCurrentTimeStamp
{
NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
[objDateformat setDateFormat:@"yyyy-MM-dd"];
NSString *strTime = [objDateformat stringFromDate:[NSDate date]];
NSString *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
NSDate *objUTCDate = [objDateformat dateFromString:strUTCTime];
long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);
NSString *strTimeStamp = [NSString stringWithFormat:@"%lld",milliseconds];
NSLog(@"The Timestamp is = %@",strTimeStamp);
}
- (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *objDate = [dateFormatter dateFromString:IN_strLocalTime];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSString *strDateTime = [dateFormatter stringFromDate:objDate];
return strDateTime;
}
What's wrong with:
clob.getSubString(1, (int) clob.length());
?
For example Oracle oracle.sql.CLOB
performs getSubString()
on internal char[]
which defined in oracle.jdbc.driver.T4CConnection
and just System.arraycopy()
and next wrap to String
... You never get faster reading than System.arraycopy()
.
UPDATE Get driver ojdbc6.jar, decompile CLOB
implementation, and study which case could be faster based on the internals knowledge.
According to the fs
documentation, fsPromises
currently provides the recursive
option on an experimental basis, which, at least in my own case on Windows, removes the directory and any files therein.
fsPromises.rmdir(path, {
recursive: true
})
Does recursive: true
remove the files on Linux and MacOS?
With ES6 syntax
import mongoose from "mongoose";
// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');
Try to use the DataColumn.SetOrdinal method. For example:
dataTable.Columns["Qty"].SetOrdinal(0);
dataTable.Columns["Unit"].SetOrdinal(1);
UPDATE: This answer received much more attention than I expected. To avoid confusion and make it easier to use I decided to create an extension method for column ordering in DataTable:
Extension method:
public static class DataTableExtensions
{
public static void SetColumnsOrder(this DataTable table, params String[] columnNames)
{
int columnIndex = 0;
foreach(var columnName in columnNames)
{
table.Columns[columnName].SetOrdinal(columnIndex);
columnIndex++;
}
}
}
Usage:
table.SetColumnsOrder("Qty", "Unit", "Id");
or
table.SetColumnsOrder(new string[]{"Qty", "Unit", "Id"});
On OSX, I'm using -f to specify the input format, -j to not attempt to set any date, and an output format specifier. For example:
$ date -j -f "%m/%d/%y %H:%M:%S %p" "8/22/15 8:15:00 am" +"%m%d%y"
082215
Your example:
$ date -j -f "%d %b %Y" "27 JUN 2011" +%Y%m%d
20110627
For an unmanaged DLL file, you need to first check if it is a 16-bit DLL file (hopefully not).
Then check the IMAGE\_FILE_HEADER.Machine
field.
Someone else took the time to work this out already, so I will just repeat here:
To distinguish between a 32-bit and 64-bit PE file, you should check IMAGE_FILE_HEADER.Machine field. Based on the Microsoft PE and COFF specification below, I have listed out all the possible values for this field: http://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/pecoff_v8.doc
IMAGE_FILE_MACHINE_UNKNOWN 0x0 The contents of this field are assumed to be applicable to any machine type
IMAGE_FILE_MACHINE_AM33 0x1d3 Matsushita AM33
IMAGE_FILE_MACHINE_AMD64 0x8664 x64
IMAGE_FILE_MACHINE_ARM 0x1c0 ARM little endian
IMAGE_FILE_MACHINE_EBC 0xebc EFI byte code
IMAGE_FILE_MACHINE_I386 0x14c Intel 386 or later processors and compatible processors
IMAGE_FILE_MACHINE_IA64 0x200 Intel Itanium processor family
IMAGE_FILE_MACHINE_M32R 0x9041 Mitsubishi M32R little endian
IMAGE_FILE_MACHINE_MIPS16 0x266 MIPS16
IMAGE_FILE_MACHINE_MIPSFPU 0x366 MIPS with FPU
IMAGE_FILE_MACHINE_MIPSFPU16 0x466 MIPS16 with FPU
IMAGE_FILE_MACHINE_POWERPC 0x1f0 Power PC little endian
IMAGE_FILE_MACHINE_POWERPCFP 0x1f1 Power PC with floating point support
IMAGE_FILE_MACHINE_R4000 0x166 MIPS little endian
IMAGE_FILE_MACHINE_SH3 0x1a2 Hitachi SH3
IMAGE_FILE_MACHINE_SH3DSP 0x1a3 Hitachi SH3 DSP
IMAGE_FILE_MACHINE_SH4 0x1a6 Hitachi SH4
IMAGE_FILE_MACHINE_SH5 0x1a8 Hitachi SH5
IMAGE_FILE_MACHINE_THUMB 0x1c2 Thumb
IMAGE_FILE_MACHINE_WCEMIPSV2 0x169 MIPS little-endian WCE v2
Yes, you may check IMAGE_FILE_MACHINE_AMD64|IMAGE_FILE_MACHINE_IA64 for 64bit and IMAGE_FILE_MACHINE_I386 for 32bit.
Create the war file in a different directory to where the content is otherwise the jar command might try to zip up the file it is creating.
#!/bin/bash
set -euo pipefail
war=app.war
src=contents
# Clean last war build
if [ -e ${war} ]; then
echo "Removing old war ${war}"
rm -rf ${war}
fi
# Build war
if [ -d ${src} ]; then
echo "Found source at ${src}"
cd ${src}
jar -cvf ../${war} *
cd ..
fi
# Show war details
ls -la ${war}
In case someone is looking I reposted my answer from: SelectListItem selected = true not working in view
After searching myself for answer to this problem - I had some hints along the way but this is the resulting solution for me. It is an extension Method. I am using MVC 5 C# 4.52 is the target. The code below sets the Selection to the First Item in the List because that is what I needed, you might desire simply to pass a string and skip enumerating - but I also wanted to make sure I had something returned to my SelectList from the DB)
Extension Method:
public static class SelectListextensions {
public static System.Web.Mvc.SelectList SetSelectedValue
(this System.Web.Mvc.SelectList list, string value)
{
if (value != null)
{
var selected = list.Where(x => x.Text == value).FirstOrDefault();
selected.Selected = true;
}
return list;
}
}
And for those who like the complete low down (like me) here is the usage. The object Category has a field defined as Name - this is the field that will show up as Text in the drop down. You can see that test for the Text property in the code above.
Example Code:
SelectList categorylist = new SelectList(dbContext.Categories, "Id", "Name");
SetSelectedItemValue(categorylist);
select list function:
private SelectList SetSelectedItemValue(SelectList source) { Category category = new Category();
SelectListItem firstItem = new SelectListItem();
int selectListCount = -1;
if (source != null && source.Items != null)
{
System.Collections.IEnumerator cenum = source.Items.GetEnumerator();
while (cenum.MoveNext())
{
if (selectListCount == -1)
{
selectListCount = 0;
}
selectListCount += 1;
category = (Category)cenum.Current;
source.SetSelectedValue(category.Name);
break;
}
if (selectListCount > 0)
{
foreach (SelectListItem item in source.Items)
{
if (item.Value == cenum.Current.ToString())
{
item.Selected = true;
break;
}
}
}
}
return source;
}
You can make this a Generic All Inclusive function / Extension - but it is working as is for me
Following on from Tomasz's answer, you can also programmatically set the shade of the entire button using the PorterDuff multiply mode. This will change the button colour rather than just the tint.
If you start with a standard grey shaded button:
button.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
will give you a red shaded button,
button.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
will give you a green shaded button etc., where the first value is the colour in hex format.
It works by multiplying the current button colour value by your colour value. I'm sure there's also a lot more you can do with these modes.
There are two main differences.
The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.
So, for a unidirectional @ManyToOne
association, it means you can only access the relationship from the child side where the foreign key resides.
If you have a unidirectional @OneToMany
association, it means you can only access the relationship from the parent side which manages the foreign key.
For the bidirectional @OneToMany
association, you can navigate the association in both ways, either from the parent or from the child side.
You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.
The second aspect is related to performance.
@OneToMany
, unidirectional associations don't perform as well as bidirectional ones.@OneToOne
, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value.@ManyToMany
, the collection type makes quite a difference as Sets
perform better than Lists
.@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
Also you can use
dirname(__DIR__, $level)
for access any folding level without traversing
The suggested answers here, including the accepted answer from rerezz which suggest adding multiple route entries work fine.
However the component will be recreated when changing between the route entries, i.e. between the route entry with the parameter and the entry without the parameter.
If you want to avoid this, you can create your own route matcher which will match both routes:
export function userPageMatcher(segments: UrlSegment[]): UrlMatchResult {
if (segments.length > 0 && segments[0].path === 'user') {
if (segments.length === 1) {
return {
consumed: segments,
posParams: {},
};
}
if (segments.length === 2) {
return {
consumed: segments,
posParams: { id: segments[1] },
};
}
return <UrlMatchResult>(null as any);
}
return <UrlMatchResult>(null as any);
}
Then use the matcher in your route config:
const routes: Routes = [
{
matcher: userPageMatcher,
component: User,
}
];
function display_c(){
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh)
}
function display_ct() {
var strcount
var currentdate = new Date();
document.getElementById('ct').innerHTML = currentdate.toDateString() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
tt = display_c();
}
id = 'ct' // Replace in Your id
onload = "display_ct();" // Type inside a Body Tag
Since we are talking about having every element exactly once, a "set" makes more sense to me.
Example with classes and IEqualityComparer implemented:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Product(int x, string y)
{
Id = x;
Name = y;
}
}
public class ProductCompare : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{ //Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Id == y.Id && x.Name == y.Name;
}
public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = product.Id.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
Now
List<Product> originalList = new List<Product> {new Product(1, "ad"), new Product(1, "ad")};
var setList = new HashSet<Product>(originalList, new ProductCompare()).ToList();
setList
will have unique elements
I thought of this while dealing with .Except()
which returns a set-difference
Here you go with:
from b in _dbContext.Burden
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }
It seems like all above answers solve the problem. One more point: instead of pd.set_option('option_name')
, you can use the (auto-complete-able)
pd.options.display.width = None
See Pandas doc: Options and Settings:
Options have a full “dotted-style”, case-insensitive name (e.g.
display.max_rows
). You can get/set options directly as attributes of the top-leveloptions
attribute:In [1]: import pandas as pd In [2]: pd.options.display.max_rows Out[2]: 15 In [3]: pd.options.display.max_rows = 999 In [4]: pd.options.display.max_rows Out[4]: 999
[...]
for the max_...
params:
max_rows
andmax_columns
are used in__repr__()
methods to decide ifto_string()
orinfo()
is used to render an object to a string. In case python/IPython is running in a terminal this can be set to 0 and pandas will correctly auto-detect the width the terminal and swap to a smaller format in case all columns would not fit vertically. The IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to do correct auto-detection. ‘None
’ value means unlimited. [emphasis not in original]
for the width
param:
Width of the display in characters. In case python/IPython is running in a terminal this can be set to
None
and pandas will correctly auto-detect the width. Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to correctly detect the width.
Panel with opacity:
public class GlassyPanel : Panel
{
const int WS_EX_TRANSPARENT = 0x20;
int opacity = 50;
public int Opacity
{
get
{
return opacity;
}
set
{
if (value < 0 || value > 100) throw new ArgumentException("Value must be between 0 and 100");
opacity = value;
}
}
protected override CreateParams CreateParams
{
get
{
var cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | WS_EX_TRANSPARENT;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
using (var b = new SolidBrush(Color.FromArgb(opacity * 255 / 100, BackColor)))
{
e.Graphics.FillRectangle(b, ClientRectangle);
}
base.OnPaint(e);
}
}
This will also checks in leap year. This is pure regex, so it's faster than any lib (also faster than moment.js). But if you gonna use a lot of dates in ur code, I do recommend to use moment.js
var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
console.log(dateRegex.test('21/01/1986'));
Here is a single-liner of how you can delete ALL browser network cache using Cache.delete()
caches.keys().then((keyList) => Promise.all(keyList.map((key) => caches.delete(key))))
Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.
Unless I'm mistaken, the above code does not take unallocated space into account, so if you really want to know when you'll hit a hard limit, you should use maxbytes.
I think the code below does that. It calculates free space as "freespace" + unallocated space.
select
free.tablespace_name,
free.bytes,
reserv.maxbytes,
reserv.bytes,
reserv.maxbytes - reserv.bytes + free.bytes "max free bytes",
reserv.datafiles
from
(select tablespace_name, count(1) datafiles, sum(maxbytes) maxbytes, sum(bytes) bytes from dba_data_files group by tablespace_name) reserv,
(select tablespace_name, sum(bytes) bytes from dba_free_space group by tablespace_name) free
where free.tablespace_name = reserv.tablespace_name;
You can use set_printoptions
to set the precision of the output:
import numpy as np
x=np.random.random(10)
print(x)
# [ 0.07837821 0.48002108 0.41274116 0.82993414 0.77610352 0.1023732
# 0.51303098 0.4617183 0.33487207 0.71162095]
np.set_printoptions(precision=3)
print(x)
# [ 0.078 0.48 0.413 0.83 0.776 0.102 0.513 0.462 0.335 0.712]
And suppress
suppresses the use of scientific notation for small numbers:
y=np.array([1.5e-10,1.5,1500])
print(y)
# [ 1.500e-10 1.500e+00 1.500e+03]
np.set_printoptions(suppress=True)
print(y)
# [ 0. 1.5 1500. ]
See the docs for set_printoptions for other options.
To apply print options locally, using NumPy 1.15.0 or later, you could use the numpy.printoptions context manager.
For example, inside the with-suite
precision=3
and suppress=True
are set:
x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
But outside the with-suite
the print options are back to default settings:
print(x)
# [ 0.07334334 0.46132615 0.68935231 0.75379645 0.62424021 0.90115836
# 0.04879837 0.58207504 0.55694118 0.34768638]
If you are using an earlier version of NumPy, you can create the context manager yourself. For example,
import numpy as np
import contextlib
@contextlib.contextmanager
def printoptions(*args, **kwargs):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
try:
yield
finally:
np.set_printoptions(**original)
x = np.random.random(10)
with printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
To prevent zeros from being stripped from the end of floats:
np.set_printoptions
now has a formatter
parameter which allows you to specify a format function for each type.
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(x)
which prints
[ 0.078 0.480 0.413 0.830 0.776 0.102 0.513 0.462 0.335 0.712]
instead of
[ 0.078 0.48 0.413 0.83 0.776 0.102 0.513 0.462 0.335 0.712]
OP didn't specify if the object is a nodeList, if it is then you can just use length method on it directly. Example:
buttons = document.querySelectorAll('[id=button)) {
console.log('Found ' + buttons.length + ' on the screen');
John O'Connor is right with the issue. The problem stays with installing ADT 17 and above. Found this link for fixing the error:
http://android.foxykeep.com/dev/how-to-fix-the-classdefnotfounderror-with-adt-17
<p>31<sup>st</sup> March 2015</p>
_x000D_
You can use
1<sup>st</sup>
2<sup>nd</sup>
3<sup>rd</sup>
4<sup>th</sup>
for positioning the suffix
There is no do-while loop in Python.
This is a similar construct, taken from the link above.
while True:
do_something()
if condition():
break
Optional method will be:
$lastID = DB::table('EXAMPLE-TABLE')
->orderBy('id', 'desc')
->first();
$lastId = $lastProduct->id;
Simple line:
bodyDoc.LoadXml(new MemoryStream(Encoding.Unicode.GetBytes(body)));
the value selected in the model takes advantage instead of the default item. (I agree I didn't read all posts)
When a CSS property shows as struck-through, it means that the crossed-out style was applied, but then overridden by a more specific selector, a more local rule, or by a later property within the same rule.
(Special cases: a style will also be shown as struck-through if a style exists in an matching rule but is commented out, or if you've manually disabled it by unchecking it within the Chrome developer tools. It will also show as crossed out, but with an error icon, if the style has a syntax error.)
For example, if a background color was applied to all div
s, but a different background color was applied to div
s with a certain id, the first color will show up but will be crossed out, as the second color has replaced it (in the property list for the div
with that id).
This has to do with contiguous memory.
Here's some info I found online for somebody asking that before, supposedly from a "VM god":
The reason we need a contiguous memory region for the heap is that we have a bunch of side data structures that are indexed by (scaled) offsets from the start of the heap. For example, we track object reference updates with a "card mark array" that has one byte for each 512 bytes of heap. When we store a reference in the heap we have to mark the corresponding byte in the card mark array. We right shift the destination address of the store and use that to index the card mark array. Fun addressing arithmetic games you can't do in Java that you get to (have to :-) play in C++.
Usually we don't have trouble getting modest contiguous regions (up to about 1.5GB on Windohs, up to about 3.8GB on Solaris. YMMV.). On Windohs, the problem is mostly that there are some libraries that get loaded before the JVM starts up that break up the address space. Using the /3GB switch won't rebase those libraries, so they are still a problem for us.
We know how to make chunked heaps, but there would be some overhead to using them. We have more requests for faster storage management than we do for larger heaps in the 32-bit JVM. If you really want large heaps, switch to the 64-bit JVM. We still need contiguous memory, but it's much easier to get in a 64-bit address space.
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
public class RadioButton extends JRadioButton {
public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
public Object[] getSelectedObjects() {
if ( isSelected() ) {
return new Object[] { RadioButton.this };
} else {
return new Object[0];
}
}
public RadioButton getButton() { return RadioButton.this; }
}
public RadioButton() { super(); setModel(new RadioButtonModel()); }
public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }
public static void main(String[] args) {
RadioButton b1 = new RadioButton("A");
RadioButton b2 = new RadioButton("B");
ButtonGroup group = new ButtonGroup();
group.add(b1);
group.add(b2);
b2.setSelected(true);
RadioButtonModel model = (RadioButtonModel)group.getSelection();
System.out.println(model.getButton().getText());
}
}
Normally yes, .gitignore
is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG
or something. In those cases you probably don't want to force that on anyone else.
A slightly more elegant way, adapting Greg Dean's function:
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
Call it like:
"pascal".toProperCase();
The only code that will work is the one that uses 'SizeToFit' as in jhibberd answer above but actually it won't pick up unless you call it in ViewDidAppear or wire it to UITextView text changed event.
For those of you who hasn't seen one valid argument against use of Thread.Sleep in SCENARIO 2, there really is one - application exit be held up by the while loop (SCENARIO 1/3 is just plain stupid so not worthy of more mentioning)
Many who pretend to be in-the-know, screaming Thread.Sleep is evil failed to mentioned a single valid reason for those of us who demanded a practical reason not to use it - but here it is, thanks to Pete - Thread.Sleep is Evil (can be easily avoided with a timer/handler)
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(ThreadFunc));
t.Start();
Console.WriteLine("Hit any key to exit.");
Console.ReadLine();
Console.WriteLine("App exiting");
return;
}
static void ThreadFunc()
{
int i=0;
try
{
while (true)
{
Console.WriteLine(Thread.CurrentThread.ThreadState.ToString() + " " + i);
Thread.Sleep(1000 * 10);
i++;
}
}
finally
{
Console.WriteLine("Exiting while loop");
}
return;
}
There's a small Java program which generates docs (adoc or md) from a yaml file.
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withSwaggerMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withOutputLanguage(Language.DE)
.build();
Swagger2MarkupConverter builder = Swagger2MarkupConverter.from(yamlFileAsString).withConfig(config).build();
return builder.toFileWithoutExtension(outFile);
Unfortunately it only supports OpenAPI 2.0 but not OpenAPI 3.0.
For whatever reason, TWO of my solutions have web projects that spontaneously uninstalled asp.net MVC somehow. I installed it from Nuget and now they both work again. This happened after a recent batch of windows updates that included .net framework updates for the version I was using (4.5.1).
Edit: From the .Net Web Development and Tools Blog:
Microsoft Asp.Net MVC Security Update MS14-059 broke my build!
We can use Angular event bindings to respond to any DOM event. The syntax is simple. We surround the DOM event name in parentheses and assign a quoted template statement to it. -- reference
Since change
is on the list of standard DOM events, we can use it:
(change)="saverange()"
In your particular case, since you're using NgModel, you could break up the two-way binding like this instead:
[ngModel]="range" (ngModelChange)="saverange($event)"
Then
saverange(newValue) {
this.range = newValue;
this.Platform.ready().then(() => {
this.rootRef.child("users").child(this.UserID).child('range').set(this.range)
})
}
However, with this approach saverange()
is called with every keystroke, so you're probably better off using (change)
.
String
objects in Java use the UTF-16 encoding that can't be modified.
The only thing that can have a different encoding is a byte[]
. So if you need UTF-8 data, then you need a byte[]
. If you have a String
that contains unexpected data, then the problem is at some earlier place that incorrectly converted some binary data to a String
(i.e. it was using the wrong encoding).
I would just query for the for
attribute instead of repetitively recursing the DOM tree.
$("input:checkbox").on("change", function() {
$("label[for='"+this.id+"']").text("TESTTTT");
});
I ran into this problem after experimenting with SignalR and then removing it from the project. To resolve I had to delete the contents of the bin folder for the site on the remote server and then publish again.
if you are using for certain text field then use the class
<style>
.inputForm{
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
}
</style>
and in html code use
<input type="text" class="inputForm">
or if u want to do this for all the input type text field means use
<style>
input[type="text"]{
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
}
</style>
and in html code
<input type="text" name="name">
for element in range(0,len(hello)):
d[element] = hello[element].strip()
This question is very old, but I found myself studying for a Microsoft Certification, and in the study book it was suggested to use:
oldElement.replaceNode(newElement)
I looked it up and it seems to only be supported in IE. Doh..
I thought I'd just add it here as a funny side note ;)
AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
new AmazonEC2Client(credentialsProvider)
.aws/credentials
[default]
aws_access_key_id =
aws_secret_access_key =
I took Jezzipin's answer and made it so that if you are scrolled when you refresh the page, the correct size applies. Also removed some stuff that isn't necessarily needed.
function sizer() {
if($(document).scrollTop() > 0) {
$('#header_nav').stop().animate({
height:'40px'
},600);
} else {
$('#header_nav').stop().animate({
height:'100px'
},600);
}
}
$(window).scroll(function(){
sizer();
});
sizer();
same as pascal answered, just if you need to use .AUTO for some reason you just need to add in your application properties:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto = update
Note the ""
at the beginning and at the end!
Run a program and pass a Long Filename
cmd /c write.exe "c:\sample documents\sample.txt"
Spaces in Program Path
cmd /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in Program Path + parameters
cmd /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
Spaces in Program Path + parameters with spaces
cmd /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch Demo1 and then Launch Demo2
cmd /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
You can also use printf to pipe the input to your script.
var=val
printf "yes\nno\nmaybe\n$var\n" | ./your_script.sh
My recommendation? Don't use jQuery at all. I had the same problem as you. I found that $('#my_input').val()
always return some weird result.
Try to use document.getElementById('my_input').valueAsNumber
instead of $("#my_input").val();
and then, use Number(your_value_retrieved)
to try to create a Number. If the value is NaN, you know certainly that that's not a number.
One thing to add is when you write a number on the input, the input will actually accept almost any character (I can write the euro sign, a dollar, and all of other special characters), so it is best to retrieve the value using .valueAsNumber
instead of using jQuery.
Oh, and BTW, that allows your users to add internationalization (i.e.: support commas instead of dots to create decimal numbers). Just let the Number()
object to create something for you and it will be decimal-safe, so to speak.
When you directly print print_r(($value['<YOUR_ARRAY>']-><YOUR_OBJECT>));
then it shows this fatal error Cannot use string offset as an object in
.
If you print like this
$var = $value['#node']-><YOU_OBJECT>;
print_r($var);
You won't get the error!!
I get this error when my project .net framework version does not match the framework version of the DLL I am linking to. In my case, I was getting:
"The type or namespace name 'UserVoice' could not be found (are you missing a using directive or an assembly reference?).
UserVoice was .Net 4.0, and my project properties were set to ".Net 4.0 Client Profile". Changing to .Net 4.0 on the project cleared the error. I hope this helps someone.
This function works in at least Firefox, and Internet Explorer. It runs any event handlers attached to the link and loads the linked page if the event handlers don't cancel the default action.
function clickLink(link) {
var cancelled = false;
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0,
false, false, false, false,
0, null);
cancelled = !link.dispatchEvent(event);
}
else if (link.fireEvent) {
cancelled = !link.fireEvent("onclick");
}
if (!cancelled) {
window.location = link.href;
}
}
it makes the assignment visible to subprocesses.
$ foo=bar
$ bash -c 'echo $foo'
$ export foo
$ bash -c 'echo $foo'
bar
You have two versions of mysql using the same port. 3306. Change the port.
How to change the mysql port for xampp?
Code:
Password = your_password
port = 3306 ---> 3307
socket = "/ xampp / mysql / mysql.sock"
and here also
Code:
The MySQL server
[ mysqld ]
port = 3306 ---> 3307
socket = "/ xampp / mysql / mysql.sock"
2. Start mysql service
If you want to append unique object, you can expand Array struct
extension Array where Element: Equatable {
mutating func appendUniqueObject(object: Generator.Element) {
if contains(object) == false {
append(object)
}
}
}
I have always used the following:
If Request.QueryString("MyQueryString") IsNot Nothing Then
But only because syntactically it reads better.
When testing for a valid QueryString entry I also use the following:
If Not String.IsNullOrEmpty(Request.QueryString("MyQueryString")) Then
These are just the methods I have always used so I could not justify their usage other than they make the most sense to me when reading back code.
The first problem is that button1
is a local variable of the main
method, so the actionPerformed
method doesn't have access to it.
The second problem is that the ActionListener
interface is implemented by the class calc
, but no instance of this class is created in the main
method.
The usual way to do what you want is to create an instance of calc
and make button1
a field of the calc
class.
I got a same problem. Below is how I solved the problem. I am working on an oracle database 12c pluggable database(pdb) on a windows 10.
-- using sqlplus to login as sysdba from a terminal; Below is an example:
sqlplus sys/@orclpdb as sysdba
-- First check your database status;
SQL> select name, open_mode from v$pdbs;
-- It shows the database is mounted in my case. If yours is not mounted, you should mount the database first.
-- Next open the database for read/write
SQL> ALTER PLUGGABLE DATABASE OPEN; (or ALTER PLUGGABLE DATABASE YOURDATABASENAME OPEN;)
-- Check the status again.
SQL> select name, open_mode from v$pdbs;
-- Now your dababase should be open for read/write and you should be able to create schemas, etc.
User.objects.filter(username='tom', groups__name='admin').exists()
That query will inform you user : "tom" whether belong to group "admin " or not
An object technically is a dictionary.
var myMappings = {
mykey1: 'myValue',
mykey2: 'myValue'
};
var myVal = myMappings['myKey1'];
alert(myVal); // myValue
You can even loop through one.
for(var key in myMappings) {
var myVal = myMappings[key];
alert(myVal);
}
There is no reason whatsoever to reinvent the wheel. And of course, assignment goes like:
myMappings['mykey3'] = 'my value';
And ContainsKey:
if (myMappings.hasOwnProperty('myKey3')) {
alert('key already exists!');
}
I suggest you follow this: http://javascriptissexy.com/how-to-learn-javascript-properly/
System.IO.File.ReadLines()
is perfect for this scenario. It returns all the lines of a file, but lets you begin iterating over the lines immediately which means it does not have to store the entire contents in memory.
Requires .NET 4.0 or higher.
foreach ($line in [System.IO.File]::ReadLines($filename)) {
# do something with $line
}
is(':visible')
checks the display
property of an element, you can use css
method.
if (!$("#singlechatpanel-1").css('visibility') === 'hidden') {
// ...
}
If you set the display
property of the element to none
then your if
statement returns true
.
See this answer. val() is comparing a string, not a numeric value.
As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.
See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512
The following lifecycle methods will be called when state changes. You can use the provided arguments and the current state to determine if something meaningful changed.
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
You have four options
Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.
Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.
Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy
syntax then Theano might be a good choice.
Here is an example using SymPy
In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2·x
In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2. 2. 2. 2. 2.]
JB hit the nail on the head. The only thing I can add is that Java 8 doesn't do pure parallel processing, it does paraquential. Yes I wrote the article and I've been doing F/J for thirty years so I do understand the issue.
Save to EPS and then convert to PDF:
saveas(gcf, 'nombre.eps', 'eps2c')
system('epstopdf nombre.eps') %Needs TeX Live (maybe it works with MiKTeX).
You will need some software that converts EPS to PDF.
#include <iostream>
using namespace std;
class matrix
{
int a[10][10],b[10][10],c[10][10],x,y,i,j;
public :
void degerler();
void ters();
};
void matrix::degerler()
{
cout << "Satirlari giriniz: "; cin >> x;
cout << "Sütunlari giriniz: "; cin >> y;
cout << "Ilk matris elamanlarini giriniz:\n\n";
for (i=1; i<=x; i++)
{
for (j=1; j<=y; j++)
{
cin >> a[i][j];
}
}
cout << "Ikinci matris elamanlarini giriniz:\n\n";
for (i=1; i<=x; i++)
{
for (j=1; j<=y; j++)
{
cin >> b[i][j];
}
}
}
void matrix::ters()
{
cout << "matrisin tersi\n";
for (i=1; i<=x; i++)
{
for (j=1; j<=y; j++)
{
if(i==j)
{
b[i][j]=1;
}
else
b[i][j]=0;
}
}
float d,k;
for (i=1; i<=x; i++)
{
d=a[i][j];
for (j=1; j<=y; j++)
{
a[i][j]=a[i][j]/d;
b[i][j]=b[i][j]/d;
}
for (int h=0; h<x; h++)
{
if(h!=i)
{
k=a[h][j];
for (j=1; j<=y; j++)
{
a[h][j]=a[h][j]-(a[i][j]*k);
b[h][j]=b[h][j]-(b[i][j]*k);
}
}
count << a[i][j] << "";
}
count << endl;
}
}
int main()
{
int secim;
char ch;
matrix m;
m.degerler();
do
{
cout << "seçiminizi giriniz\n";
cout << " 1. matrisin tersi\n";
cin >> secim;
switch (secim)
{
case 1:
m.ters();
break;
}
cout << "\nBaska bir sey yap/n?";
cin >> ch;
}
while (ch!= 'n');
cout << "\n";
return 0;
}
String path = "C:\\Documents and Settings\\Manoj\\Desktop";
String javaPath = path.replace("\\", "/"); // Create a new variable
or
path = path.replace("\\", "/"); // Just use the existing variable
String
s are immutable. Once they are created, you can't change them. This means replace
returns a new String where the target("\\"
) is replaced by the replacement("/"
). Simply calling replace
will not change path
.
The difference between replaceAll
and replace
is that replaceAll will search for a regex, replace doesn't.
First of all, return
is a keyword and exit
is a function.
That said, here's a simplest of explanations.
return
It returns a value from a function.
exit
It exits out of or abandons the current shell.
If you don't need to display exact result "running" / "not runnuning", you could simply:
ps notepad -ErrorAction SilentlyContinue | kill -PassThru
If the process was not running, you'll get no results. If it was running, you'll receive get-process
output, and the process will be stopped.
My solution is similar to ATom's one, but easier to implement. You don't need to create a class that shadows FirebaseMessagingService completely, you can just override the method that receives the Intent (which is public, at least in version 9.6.1) and take the information to be displayed from the extras. The "hacky" part is that the method name is indeed obfuscated and is gonna change every time you update the Firebase sdk to a new version, but you can look it up quickly by inspecting FirebaseMessagingService with Android Studio and looking for a public method that takes an Intent as the only parameter. In version 9.6.1 it's called zzm. Here's how my service looks like:
public class MyNotificationService extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage) {
// do nothing
}
@Override
public void zzm(Intent intent) {
Intent launchIntent = new Intent(this, SplashScreenActivity.class);
launchIntent.setAction(Intent.ACTION_MAIN);
launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* R equest code */, launchIntent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setLargeIcon(rawBitmap)
.setContentTitle(intent.getStringExtra("gcm.notification.title"))
.setContentText(intent.getStringExtra("gcm.notification.body"))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Try this code in stead of android.r.layout.simple_list_item_single_choice
create your own layout:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:gravity="center_vertical"
android:padding="5dip"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/black"
android:textStyle="bold">
</CheckedTextView>
I use System.Web.HttpUtility.JavaScriptStringEncode
string quoted = HttpUtility.JavaScriptStringEncode(input);
In the service project do the following:
Now you need to make a setup project. The best thing to do is use the setup wizard.
Right click on your solution and add a new project: Add > New Project > Setup and Deployment Projects > Setup Wizard
a. This could vary slightly for different versions of Visual Studio. b. Visual Studio 2010 it is located in: Install Templates > Other Project Types > Setup and Deployment > Visual Studio Installer
On the second step select "Create a Setup for a Windows Application."
On the 3rd step, select "Primary output from..."
Click through to Finish.
Next edit your installer to make sure the correct output is included.
You can edit the installer output name by right clicking the Installer project in your solution and select Properties. Change the 'Output file name:' to whatever you want. By selecting the installer project as well and looking at the properties windows, you can edit the Product Name
, Title
, Manufacturer
, etc...
Next build your installer and it will produce an MSI and a setup.exe. Choose whichever you want to use to deploy your service.
You can find the most up to date answer for the value in your project just execute the
mvn3 help:effective-pom
command and find the <build> ... <directory>
tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.
I had the same problem. Got the following message when I tried to commit:
waiting for lock on working directory of <MyProject> held by '...'
hg debuglock
showed this:
lock: free
wlock: (66722s)
So I did the following command, and that fixed the problem for me:
hg debuglocks -W
Using Win7 and TortoiseHg 4.8.7.
http://codepen.io/Edo_B/pen/cLbrt
Using:
that's it.
I also believe this could be done dynamically for any screen if using canvas to copy the current dom and blurring it.
to get domain/hostname and Origin*
url = 'https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url'
hostname = url.split('/')[2] # stackoverflow.com
origin = '/'.join(url.split('/')[:3]) # https://stackoverflow.com
*Origin
is used in XMLHttpRequest
headers
See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.
Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.
The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.
It does look like the checkout --orphan
is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init
a repo, set up a remote
tracking branch (you do want the one branch only?), and then fetch
that single branch, which feels long winded with more opportunity for mistakes.
Edit: For the 'clone' step see this answer
Remove semicolon and you can see that link: http://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html
title = u"Klüft skräms inför på fédéral électoral große"
import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
'Kluft skrams infor pa federal electoral groe'
I believe this is help full for who are getting this below Exception on to pumping data through logstash Error: logstash.inputs.jdbc - Exception when executing JDBC query {:exception=>#}
Answer:jdbc:mysql://localhost:3306/database_name?zeroDateTimeBehavior=convertToNull"
or if you are working with mysql
I had the same issue.For me the problem was how to configure a cache limit to images.And i came across this site which gave some insights to the procedure on how the issue can be handled.Hope it will be helpful for you too Link:[https://varvy.com/pagespeed/cache-control.html]
If using version 8 and you edit the my.ini I found that Notepad is putting 3 hex characters at the beginning of the my.ini file. EF BB BF. Deleting the 3 characters from the beginning of the file in a hex editor fixes the problem.
In version 8 they are accidentally putting Unicode characters in the ini file. This is causing Notepad to save the file with Byte order mark characters.
The following line in the file is the culprit "The line # range from 1 to 2^32 - 1. “Unique” means that each ID must be different." has 3 Unicode characters. This is causing notepad to append the byte order mark to the text file.
When you don't want to change the link (e.g. foo.php?id=1&id=2&id=3
) you could probably do something like this (although there might be a better way...):
$id_arr = array();
foreach (explode("&", $_SERVER['QUERY_STRING']) as $tmp_arr_param) {
$split_param = explode("=", $tmp_arr_param);
if ($split_param[0] == "id") {
$id_arr[] = urldecode($split_param[1]);
}
}
print_r($id_arr);
To print a range of line, in this case from line 4 to 7
import csv with open('california_housing_test.csv') as csv_file: data = csv.reader(csv_file) for row in list(data)[4:7]: print(row)
You can't add a new unique auto-generated ID to a SharePoint list, but there already is one there! If you edit the "All Items" view you will see a list of columns that do not have the display option checked.
There are quite a few of these columns that exist but that are never displayed, like "Created By" and "Created". These fields are used within SharePoint, but they are not displayed by default so as not to clutter up the display. You can't edit these fields, but you can display them to the user. if you check the "Display" box beside the ID field you will get a unique and auto-generated ID field displayed in your list.
Check out: Unique ID in SharePoint list
Define the helper:
remove-warning () {
grep -v 'mysql: [Warning] Using a password on the command line interface can be insecure.'
}
Use it:
mysql -u $user -p$password -e "statement" 2>&1 | remove-warning
Tachaan! Your code is clean and nice to read
(tested with bash)
Firefox is more stringent than other browsers and will require proper installation of an intermediate server certificate. This can be supplied by the cert authority the certificate was purchased from. the intermediate cert is typically installed in the same location as the server cert and requires the proper entry in the httpd.conf file.
while many are chastising Firefox for it's (generally) exclusive 'flagging' of this, it's actually demonstrating a higher level of security standards.
The u- prefix just means that you have a Unicode string. When you really use the string, it won't appear in your data. Don't be thrown by the printed output.
For example, try this:
print mail_accounts[0]["i"]
You won't see a u.
//This prototype function allows you to remove even array from array
Array.prototype.remove = function(x) {
var i;
for(i in this){
if(this[i].toString() == x.toString()){
this.splice(i,1)
}
}
}
Example of using
var arr = [1,2,[1,1], 'abc'];
arr.remove([1,1]);
console.log(arr) //[1, 2, 'abc']
var arr = [1,2,[1,1], 'abc'];
arr.remove(1);
console.log(arr) //[2, [1,1], 'abc']
var arr = [1,2,[1,1], 'abc'];
arr.remove('abc');
console.log(arr) //[1, 2, [1,1]]
To use this prototype function you need to paste it in your code. Then you can apply it to any array with 'dot notation':
someArr.remove('elem1')
Similar to unutbu's answer, you can use numpy's arange function, which is analog to Python's intrinsic function range
. Notice that the end point is not included, as in range
:
>>> import numpy as np
>>> a = np.arange(0,5, 0.5)
>>> a
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
>>> a = np.arange(0,5, 0.5) # returns a numpy array
>>> a
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
>>> a.tolist() # if you prefer it as a list
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
I know this is an old question, but the problem is not going away soon. CSV files are easy to generate from most programming languages, rather small, human-readable in a crunch with a plain text editor, and ubiquitous.
The problem is not only with dates in text fields, but anything numeric also gets converted from text to numbers. A couple of examples where this is problematic:
which sometimes can start with one or more zeroes (0), which get thrown away when converted to numeric. Or the value contains characters that can be confused with mathematical operators (as in dates: /, -).
Two cases that I can think of that the "prepending =" solution, as mentioned previously, might not be ideal is
If one pre/appends a non-numeric and/or non-date character in the value, the value will be recognized as text and not converted. A non-printing character would be good as it will not alter the displayed value. However, the plain old space character (\s, ASCII 32) doesn't work for this as it gets chopped off by Excel and then the value still gets converted. But there are various other printing and non-printing space characters that will work well. The easiest however is to append (add after) the simple tab character (\t, ASCII 9).
Benefits of this approach:
If there's a reason you don't want to use the tab, look in an Unicode table for something else suitable.
might be to generate XML files, for which a certain format also is accepted for import by newer MS Excel versions, and which allows a lot more options similar to .XLS format, but I don't have experience with this.
So there are various options. Depending on your requirements/application, one might be better than another.
It needs to be said that newer versions (2013+) of MS Excel don't open the CSV in spreadsheet format any more - one more speedbump in one's workflow making Excel less useful... At least, instructions exist for getting around it. See e.g. this Stackoverflow: How to correctly display .csv files within Excel 2013? .
The source for String.valueOf shows this:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Not that it matters much, but I would use toString.
In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.
Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.
Just for completeness, you can get a list of kernels with jupyter kernelspec list
, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel
. If you do not see everything in this list when you run jupyter kernelspec list
, try looking in common Jupyter folders:
ls ~/.local/share/jupyter/kernels # usually where local kernels go
ls /usr/local/share/jupyter/kernels # usually where system-wide kernels go
ls /usr/share/jupyter/kernels # also where system-wide kernels can go
Also, you can delete a kernel with jupyter kernelspec remove
or jupyter kernelspec uninstall
. The latter is an alias for remove
. From the in-line help text for the command:
uninstall
Alias for remove
remove
Remove one or more Jupyter kernelspecs by name.
You can use the short version:
File.write('/path/to/file', 'Some glorious content')
It returns the length written; see ::write for more details and options.
To append to the file, if it already exists, use:
File.write('/path/to/file', 'Some glorious content', mode: 'a')
Some worthwhile subtleties...
\33[2K
erases the entire line your cursor is currently on
\033[A
moves your cursor up one line, but in the same column i.e. not to the start of the line
\r
brings your cursor to the beginning of the line (r is for carriage return N.B. carriage returns do not include a newline so cursor remains on the same line) but does not erase anything
In xterm specifically, I tried the replies mentioned above and the only way I found to erase the line and start again at the beginning is the sequence (from the comment above posted by @Stephan202 as well as @vlp and @mantal) \33[2K\r
On an implementation note, to get it to work properly for example in a countdown scenario since I wasn't using a new line character '\n'
at the end of each fprintf()
, so I had to fflush()
the stream each time (to give you some context, I started xterm using a fork on a linux machine without redirecting stdout, I was just writing to the buffered FILE pointer fdfile
with a non-blocking file descriptor I had sitting on the pseudo terminal address which in my case was /dev/pts/21
):
fprintf(fdfile, "\33[2K\rT minus %d seconds...", i);
fflush(fdfile);
Note that I used both the \33[2K sequence to erase the line followed by the \r
carriage return sequence to reposition the cursor at the beginning of the line. I had to fflush()
after each fprintf()
because I don't have a new line character at the end '\n'
. The same result without needing fflush() would require the additional sequence to go up a line:
fprintf(fdfile, "\033[A\33[2K\rT minus %d seconds...\n", i);
Note that if you have something on the line immediately above the line you want to write on, it will get over-written with the first fprintf(). You would have to leave an extra line above to allow for the first movement up one line:
i = 3;
fprintf(fdfile, "\nText to keep\n");
fprintf(fdfile, "Text to erase****************************\n");
while(i > 0) { // 3 second countdown
fprintf(fdfile, "\033[A\33[2KT\rT minus %d seconds...\n", i);
i--;
sleep(1);
}
RewriteBase
is only applied to the target of a relative rewrite rule.
Using RewriteBase like this...
RewriteBase /folder/
RewriteRule a\.html b.html
is essentially the same as...
RewriteRule a\.html /folder/b.html
But when the .htaccess file is inside /folder/
then this also points to the same target:
RewriteRule a\.html b.html
Although the docs imply always using a RewriteBase
, Apache usually detects it correctly for paths under the DocumentRoot unless:
You are using Alias
directives
You are using .htaccess rewrite rules to perform HTTP redirects (rather than just silent rewriting) to relative URLs
In these cases, you may find that you need to specify the RewriteBase.
However, since it's a confusing directive, it's generally better to simply specify absolute (aka 'root relative') URIs in your rewrite targets. Other developers reading your rules will grasp these more easily.
Quoting from Jon Lin's excellent in-depth answer here:
In an htaccess file, mod_rewrite works similar to a <Directory>
or <Location>
container. and the RewriteBase
is used to provide a relative path base.
For example, say you have this folder structure:
DocumentRoot
|-- subdir1
`-- subdir2
`-- subsubdir
So you can access:
http://example.com/
(root)http://example.com/subdir1
(subdir1)http://example.com/subdir2
(subdir2)http://example.com/subdir2/subsubdir
(subsubdir)The URI that gets sent through a RewriteRule
is relative to the directory containing the htaccess file. So if you have:
RewriteRule ^(.*)$ -
/a/b/c/d
, then the captured URI ($1
) is a/b/c/d
. subdir2
and the request is /subdir2/e/f/g
then the captured URI is e/f/g
. subsubdir
, and the request is /subdir2/subsubdir/x/y/z
, then the captured URI is x/y/z
. The directory that the rule is in has that part stripped off of the URI. The rewrite base has no affect on this, this is simply how per-directory works.
What the rewrite base does do, is provide a URL-path base (not a file-path base) for any relative paths in the rule's target. So say you have this rule:
RewriteRule ^foo$ bar.php [L]
The bar.php
is a relative path, as opposed to:
RewriteRule ^foo$ /bar.php [L]
where the /bar.php
is an absolute path. The absolute path will always be the "root" (in the directory structure above). That means that regardless of whether the rule is in the "root", "subdir1", "subsubdir", etc. the /bar.php
path always maps to http://example.com/bar.php
.
But the other rule, with the relative path, it's based on the directory that the rule is in. So if
RewriteRule ^foo$ bar.php [L]
is in the "root" and you go to http://example.com/foo
, you get served http://example.com/bar.php
. But if that rule is in the "subdir1" directory, and you go to http://example.com/subdir1/foo
, you get served http://example.com/subdir1/bar.php
. etc. This sometimes works and sometimes doesn't, as the documentation says, it's supposed to be required for relative paths, but most of the time it seems to work. Except when you are redirecting (using the R
flag, or implicitly because you have http://host
in your rule's target). That means this rule:
RewriteRule ^foo$ bar.php [L,R]
if it's in the "subdir2" directory, and you go to http://example.com/subdir2/foo
, mod_rewrite will mistake the relative path as a file-path instead of a URL-path and because of the R
flag, you'll end up getting redirected to something like: http://example.com/var/www/localhost/htdocs/subdir1
. Which is obviously not what you want.
This is where RewriteBase
comes in. The directive tells mod_rewrite what to append to the beginning of every relative path. So if I have:
RewriteBase /blah/
RewriteRule ^foo$ bar.php [L]
in "subsubdir", going to http://example.com/subdir2/subsubdir/foo
will actually serve me http://example.com/blah/bar.php
. The "bar.php" is added to the end of the base. In practice, this example is usually not what you want, because you can't have multiple bases in the same directory container or htaccess file.
In most cases, it's used like this:
RewriteBase /subdir1/
RewriteRule ^foo$ bar.php [L]
where those rules would be in the "subdir1" directory and
RewriteBase /subdir2/subsubdir/
RewriteRule ^foo$ bar.php [L]
would be in the "subsubdir" directory.
This partly allows you to make your rules portable, so you can drop them in any directory and only need to change the base instead of a bunch of rules. For example if you had:
RewriteEngine On
RewriteRule ^foo$ /subdir1/bar.php [L]
RewriteRule ^blah1$ /subdir1/blah.php?id=1 [L]
RewriteRule ^blah2$ /subdir1/blah2.php [L]
...
such that going to http://example.com/subdir1/foo
will serve http://example.com/subdir1/bar.php
etc. And say you decided to move all of those files and rules to the "subsubdir" directory. Instead of changing every instance of /subdir1/
to /subdir2/subsubdir/
, you could have just had a base:
RewriteEngine On
RewriteBase /subdir1/
RewriteRule ^foo$ bar.php [L]
RewriteRule ^blah1$ blah.php?id=1 [L]
RewriteRule ^blah2$ blah2.php [L]
...
And then when you needed to move those files and the rules to another directory, just change the base:
RewriteBase /subdir2/subsubdir/
and that's it.
Above answers are very elegant. I have written this function long back where i was also struggling to concatenate two dataframe with distinct columns.
Suppose you have dataframe sdf1 and sdf2
from pyspark.sql import functions as F
from pyspark.sql.types import *
def unequal_union_sdf(sdf1, sdf2):
s_df1_schema = set((x.name, x.dataType) for x in sdf1.schema)
s_df2_schema = set((x.name, x.dataType) for x in sdf2.schema)
for i,j in s_df2_schema.difference(s_df1_schema):
sdf1 = sdf1.withColumn(i,F.lit(None).cast(j))
for i,j in s_df1_schema.difference(s_df2_schema):
sdf2 = sdf2.withColumn(i,F.lit(None).cast(j))
common_schema_colnames = sdf1.columns
sdk = \
sdf1.select(common_schema_colnames).union(sdf2.select(common_schema_colnames))
return sdk
sdf_concat = unequal_union_sdf(sdf1, sdf2)
I had the exact same problem you describe above (Galaxy Nexus on t-mobile USA) it is because mobile data is turned off.
In Jelly Bean it is: Settings > Data Usage > mobile data
Note that I have to have mobile data turned on PRIOR to sending an MMS OR receiving one. If I receive an MMS with mobile data turned off, I will get the notification of a new message and I will receive the message with a download button. But if I do not have mobile data on prior, the incoming MMS attachment will not be received. Even if I turn it on after the message was received.
For some reason when your phone provider enables you with the ability to send and receive MMS you must have the Mobile Data enabled, even if you are using Wifi, if the Mobile Data is enabled you will be able to receive and send MMS, even if Wifi is showing as your internet on your device.
It is a real pain, as if you do not have it on, the message can hang a lot, even when turning on Mobile Data, and might require a reboot of the device.
$> printf "%x%x\n" "'A" "'a"
4161
You can construct a functions kwargs on demand:
kwargs = {}
kwargs[str("%s__icontains" % field)] = some_value
some_function(**kwargs)
The str() call is somehow needed, since python complains otherwise that it is no string. Don't know why ;) I use this for a dynamic filters within Djangos object model:
result = model_class.objects.filter(**kwargs)
You inflate an XML resource. See the LayoutInflater doc .
If your layout is in a mylayout.xml, you would do something like:
View view;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.mylayout, null);
RelativeLayout item = (RelativeLayout) view.findViewById(R.id.item);
ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]
I always have to use the brackets when I use the ALTER SCHEMA
query in SQL, or I get an error message.
You can return an object containing both values — there's nothing wrong with that.
Another strategy is to keep the value, via closures, instead of passing it through:
somethingAsync().then(afterSomething);
function afterSomething(amazingData) {
return processAsync(amazingData).then(function (processedData) {
// both amazingData and processedData are in scope here
});
}
Fully rather than partially inlined form (equivalent, arguably more consistent):
somethingAsync().then(function (amazingData) {
return processAsync(amazingData).then(function (processedData) {
// both amazingData and processedData are in scope here
});
}
Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.
You will never get your app approved by Apple if it is not developed using Xcode. Never. And if you do hack the SDK to develop on Linux and Apple finds out, don't be surprised when you are served. I am a member of the ADC and the iPhone developer program. Trust, Apple is VERY serious about this.
Don't take the risk, Buy a Macbook or Mac mini (yes a mini can run Xcode - though slowly - boost the RAM if you go with the mini). Also, while I've seen OS X hacked to run on VMware I've never seen anyone running Xcode on VM. So good luck. And I'd check the EULA before you go through the trouble.
PS: After reading the above, yes I agree If you do hack the SDK and develop on Linux at least do the final packaging on a Mac. And submit it via a Mac. Apple doesn't run through the code line by line so i doubt they'd catch that. But man, that's a lot of if's and work. Be fun to do though. :)
I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.
See inspect.getmembers(object[, predicate])
.
Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.
>>> [name for name,thing in inspect.getmembers([])]
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__',
'__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__','__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__',
'__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index',
'insert', 'pop', 'remove', 'reverse', 'sort']
>>>
Using CentOS7, logs are available using the command journalctl -u docker
. Answering distinctly, because @sabin's answer might be accurate for older versions of CentOS but was not true for me.
systemd has its own logging system called the journal. The logs for the docker daemon can be viewed using journalctl -u docker
This problem can also arise if you include jQuery more than once.
MarginTop
should be marginTop
.
For a clear understanding, please take a look at my codepen implementations https://codepen.io/serdarsenay/pen/XELWqN
Biggest difference is the need to sort your sample before applying binary search, therefore for most "normal sized" (meaning to be argued) samples will be quicker to search with a linear search algorithm.
Here is the javascript code, for html and css and full running example please refer to above codepen link.
var unsortedhaystack = [];
var haystack = [];
function init() {
unsortedhaystack = document.getElementById("haystack").value.split(' ');
}
function sortHaystack() {
var t = timer('sort benchmark');
haystack = unsortedhaystack.sort();
t.stop();
}
var timer = function(name) {
var start = new Date();
return {
stop: function() {
var end = new Date();
var time = end.getTime() - start.getTime();
console.log('Timer:', name, 'finished in', time, 'ms');
}
}
};
function lineerSearch() {
init();
var t = timer('lineerSearch benchmark');
var input = this.event.target.value;
for(var i = 0;i<unsortedhaystack.length - 1;i++) {
if (unsortedhaystack[i] === input) {
document.getElementById('result').innerHTML = 'result is... "' + unsortedhaystack[i] + '", on index: ' + i + ' of the unsorted array. Found' + ' within ' + i + ' iterations';
console.log(document.getElementById('result').innerHTML);
t.stop();
return unsortedhaystack[i];
}
}
}
function binarySearch () {
init();
sortHaystack();
var t = timer('binarySearch benchmark');
var firstIndex = 0;
var lastIndex = haystack.length-1;
var input = this.event.target.value;
//currently point in the half of the array
var currentIndex = (haystack.length-1)/2 | 0;
var iterations = 0;
while (firstIndex <= lastIndex) {
currentIndex = (firstIndex + lastIndex)/2 | 0;
iterations++;
if (haystack[currentIndex] < input) {
firstIndex = currentIndex + 1;
//console.log(currentIndex + " added, fI:"+firstIndex+", lI: "+lastIndex);
} else if (haystack[currentIndex] > input) {
lastIndex = currentIndex - 1;
//console.log(currentIndex + " substracted, fI:"+firstIndex+", lI: "+lastIndex);
} else {
document.getElementById('result').innerHTML = 'result is... "' + haystack[currentIndex] + '", on index: ' + currentIndex + ' of the sorted array. Found' + ' within ' + iterations + ' iterations';
console.log(document.getElementById('result').innerHTML);
t.stop();
return true;
}
}
}
service: It runs in the background on your system. For example,
background process: chef making soup
IntentService:- it's consecutive service.. (i.e) when you order many food items at a time to server but the server delivers those items one by one and not deliver them all at once.
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
yes, safe to delete, my script searches and nukes every instance it finds, easily modified to a local directory
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
for drive in Swap Media OSX_10.11.6/$HOME
do
pushd /Volumes/${drive} &> /dev/null
gfind . -depth -name 'DerivedData'|xargs -I '{}' /bin/rm -fR '{}'
popd &> /dev/null
done
i was having same problem with this error. It turn out my Kenel.php is having a wrong syntax when i try to comply with wrong php8 syntax
The line should be
protected $commands = [
//
];
instead of
protected array $commands = [
//
];
For anyone experiencing this in angular 9+
This issue can also be experienced if you do not declare or import the component that declares your component.
Lets consider a situation where you intend to use ng-select
but you forget to import it Angular will throw the error 'No value accessor...'
I have reproduced this error in the Below stackblitz demo.
Nothing worked for me, but only one thing: I used sudo in front of the command and it is working fine.
Note: This is not unicode compliant.
"IU".split('')
results in the 4 character array["I", "?", "?", "u"]
which can lead to dangerous bugs. See answers below for safe alternatives.
Just split it by an empty string.
var output = "Hello world!".split('');_x000D_
console.log(output);
_x000D_
See the String.prototype.split()
MDN docs.
Probably a duplicate of this post: A customized input text box in html/html5
input {_x000D_
border: 0;_x000D_
outline: 0;_x000D_
background: transparent;_x000D_
border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
Rails doesnt like the using of ^ and $ for some security reasons , probably its better to use \A and \z to set the beginning and the end of the string
you could do something like so:
if (value = /* sic */ some_function()){
use_value(value)
}
They are not synonyms.
display:none
removes the element from the normal flow of the page, allowing other elements to fill in.
visibility:hidden
leaves the element in the normal flow of the page such that is still occupies space.
Imagine you are in line for a ride at an amusement park and someone in the line gets so rowdy that security plucks them from the line. Everyone in line will then move forward one position to fill the now empty slot. This is like display:none
.
Contrast this with the similar situation, but that someone in front of you puts on an invisibility cloak. While viewing the line, it will look like there is an empty space, but people can't really fill that empty looking space because someone is still there. This is like visibility:hidden
.
A dirty fix: Add $(VC_IncludePath);$(WindowsSDK_IncludePath); into project Properties / C/C++ / General / Additional include directories
For those who get this (terribly unclear) error:
COPY failed: stat /var/lib/docker/tmp/docker-builderXXXXXXX/abc.txt: no such file or directory
There could be loads of reasons, including:
context
overwrites the context of the Dockerfile. Your COPY statements now need to navigate a path relative to what is defined in docker-compose.yml instead of relative to your Dockerfile.COPY abc.txt /app #This won't work
.dockerignore
or .gitignore
files (be wary of wildcards)Sometimes WORKDIR /abc
followed by COPY . xyz/
works where COPY /abc xyz/
fails, but it's a bit ugly.
Unfortunately I have a unique build (stuck with Gentoo for the moment) of PHP 5.5, and what I found was that
$xml->tagName['attribute']
was the only solution that worked. I tried all of Bora's methods above, including the 'Right & Quick' format, and they all failed.
The fact that this is the easiest format is a plus, but didn't enjoy thinking I was insane trying all of the formats others were saying worked.
Njoy for what its worth (did I mention unique build?).
Check an ASCII table.
It stands for CR
, or Carriage Return, AKA the Return key.
No need for IDesignTimeDbContextFactory
.
Run
add-migration initial -verbose
that will reveal the details under
An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider.
warning, which is the root cause of the problem.
In my case, problem was, having ApplicationRole : IdentityRole<int>
and invoking services.AddIdentity<ApplicationUser, IdentityRole>()
which was causing below error
System.ArgumentException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,
TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.
---> System.TypeLoadException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.UserStoreBase`8[TUser,TRole,TKey,TUserClaim,
TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TRole'.