when you are dealing with popups window.opener plays an important role, because we have to deal with fields of parent page as well as child page, when we have to use values on parent page we can use window.opener or we want some data on the child window or popup window at the time of loading then again we can set the values using window.opener
The simple solution is to measure the width and height of the content area, and then use those measurements to calculate the bottom padding percentage.
In this case, the measurements are 1680 x 720 px, so the padding on the bottom is 720 / 1680 = 0.43 * 100, which comes out to 43%.
.canvas-container {
position: relative;
padding-bottom: 43%; // (720 ÷ 1680 = 0.4286 = 43%)
height: 0;
overflow: hidden;
}
.canvas-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
You can access elements of parent window from within an iframe by using window.parent
like this:
// using jquery
window.parent.$("#element_id");
Which is the same as:
// pure javascript
window.parent.document.getElementById("element_id");
And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top
like this:
// using jquery
window.top.$("#element_id");
Which is the same as:
// pure javascript
window.top.document.getElementById("element_id");
Using jQuery you can use contents()
. For example:
var inside = $('#one').contents();
If your iframe is in the same domain as your parent page you can access the elements using document.frames
collection.
// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on document.frames['myIFrame'].document like you are working on
// normal document object in JS
window.frames['myIFrame'].document.getElementById('myIFrameElemId')
If your iframe is not in the same domain the browser should prevent such access for security reasons.
You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :
<iframe>
javascript access parent DOM across domains?To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.
The Same origin policy page on wikipedia brings some informations about that security measure :
In a nutshell, the policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions — but prevents access to most methods and properties across pages on different sites.
A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.
It's working for me with little twist. In my case I have to populate value from POPUP JS to PARENT WINDOW form.
So I have used $('#ee_id',window.opener.document).val(eeID);
Excellent!!!
This thread is misleading. Tried commenting on Lucas Ramadan's answer, but I don't have the right privileges yet, so I'll just put this here.
Batch normalization works best after the activation function, and here or here is why: it was developed to prevent internal covariate shift. Internal covariate shift occurs when the distribution of the activations of a layer shifts significantly throughout training. Batch normalization is used so that the distribution of the inputs (and these inputs are literally the result of an activation function) to a specific layer doesn't change over time due to parameter updates from each batch (or at least, allows it to change in an advantageous way). It uses batch statistics to do the normalizing, and then uses the batch normalization parameters (gamma and beta in the original paper) "to make sure that the transformation inserted in the network can represent the identity transform" (quote from original paper). But the point is that we're trying to normalize the inputs to a layer, so it should always go immediately before the next layer in the network. Whether or not that's after an activation function is dependent on the architecture in question.
I think this is caused by force-quitting your app on the iPhone prior to pressing the stop button in Xcode. Sometimes when you press the stop button in Xcode, then it takes extra time to quit the app if it hung. But just be patient, it will eventually quit most of the time.
I've found the solution in this thread
@(ViewContext.RouteData.Values["parameterName"])
What you can do is use nltk to tokenize words and then store all of the words in a list, here's what I did. If you don't know nltk; it stands for natural language toolkit and is used to process natural language. Here's some resource if you wanna get started [http://www.nltk.org/book/]
import nltk
from nltk.tokenize import word_tokenize
file = open("abc.txt",newline='')
result = file.read()
words = word_tokenize(result)
for i in words:
print(i)
The output will be this:
09807754
18
n
03
aristocrat
0
blue_blood
0
patrician
There are two options here.
One is to do an interactive rebase and edit the merge commit, redo the merge manually and continue the rebase.
Another is to use the --rebase-merges
option on git rebase
, which is described as follows from the manual:
By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually."
To create a popup you'll need the following script:
<script language="javascript" type="text/javascript">
function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}
</script>
Then, you link to it by:
<a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>
If you want you can call the function directly from document.ready also. Or maybe from another function.
This is my "crutches" solution by using html and css. There used 2 tables and fixed width of tables and table cell`s
https://jsfiddle.net/babaikawow/s2xyct24/1/
HTML:
<div class="container">
<table class="table" border = 1; > <!-- fixed width header -->
<thead >
<tr>
<th class="tbDataId" >?</th>
<th class="tbDataName">?????????</th>
<th class="tbDataData">????</th>
<th class="tbDataData">?????? ??</th>
<th class="tbDataDiseases">????????1</th>
<th class="tbDataDiseases">????????2</th>
<th class="tbDataDiseases">????????3</th>
<th class="tbDataDiseases">????????4</th>
<th class="tbDataDiseases">????????5</th>
</tr>
</thead>
</table>
<div class="scrollTable"> <!-- scrolling block -->
<table class="table" border = 1;>
<tbody>
<tr>
<td class="tbDataId" >?</td>
<td class="tbDataName">?????????</td>
<td class="tbDataData">????</td>
<td class="tbDataData">?????? ??</td>
<td class="tbDataDiseases">????????1</td>
<td class="tbDataDiseases">????????2</td>
<td class="tbDataDiseases">????????3</td>
<td class="tbDataDiseases">????????4</td>
<td class="tbDataDiseases">????????5</td>
</tr>
<tr>
<td class="tbDataId" >?</td>
<td class="tbDataName">?????????</td>
<td class="tbDataData">????</td>
<td class="tbDataData">?????? ??</td>
<td class="tbDataDiseases">????????1</td>
<td class="tbDataDiseases">????????2</td>
<td class="tbDataDiseases">????????3</td>
<td class="tbDataDiseases">????????4</td>
<td class="tbDataDiseases">????????5</td>
</tr>
<tr>
<td class="tbDataId" >?</td>
<td class="tbDataName">?????????</td>
<td class="tbDataData">????</td>
<td class="tbDataData">?????? ??</td>
<td class="tbDataDiseases">????????1</td>
<td class="tbDataDiseases">????????2</td>
<td class="tbDataDiseases">????????3</td>
<td class="tbDataDiseases">????????4</td>
<td class="tbDataDiseases">????????5</td>
</tr>
<tr>
<td class="tbDataId" >?</td>
<td class="tbDataName">?????????</td>
<td class="tbDataData">????</td>
<td class="tbDataData">?????? ??</td>
<td class="tbDataDiseases">????????1</td>
<td class="tbDataDiseases">????????2</td>
<td class="tbDataDiseases">????????3</td>
<td class="tbDataDiseases">????????4</td>
<td class="tbDataDiseases">????????5</td>
</tr>
<tr>
<td class="tbDataId" >?</td>
<td class="tbDataName">?????????</td>
<td class="tbDataData">????</td>
<td class="tbDataData">?????? ??</td>
<td class="tbDataDiseases">????????1</td>
<td class="tbDataDiseases">????????2</td>
<td class="tbDataDiseases">????????3</td>
<td class="tbDataDiseases">????????4</td>
<td class="tbDataDiseases">????????5</td>
</tr>
</tbody>
</table>
</div>
</div>
CSS:
*{
box-sizing: border-box;
}
.container{
width:1000px;
}
.scrollTable{
overflow: scroll;
overflow-x: hidden;
height: 100px;
}
table{
margin: 0px!important;
width:983px!important;
border-collapse: collapse;
}
/* Styles of the th and td */
/* Id */
.tbDataId{
width:5%;
}
/* ????,
?????? ?? */
.tbDataData{
/*width:170px;*/
width: 15%;
}
/* ? ? ? */
.tbDataName{
width: 15%;
}
/*???????? */
.tbDataDiseases{
width:10%;
}
found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:
d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)
I don't know when exactly the tokens expire, but they do, otherwise there wouldn't be an option to give offline permissions.
Anyway, sometimes requiring the user to give offline permissions is an overkill. Depending on your needs, maybe it's enough that the token remains valid as long as the website is opened in the user's browser. For this there may be a simpler solution - relogging the user in periodically using an iframe: facebook auto re-login from cookie php
Worked for me...
In newer version of windows the Certuil has [CertificateStoreName] where we can give the store name. In earlier version windows this was not possible.
Installing *.pfx certificate: certutil -f -p "" -enterprise -importpfx root ""
Installing *.cer certificate: certutil -addstore -enterprise -f -v root ""
For more details below command can be executed in windows cmd. C:>certutil -importpfx -? Usage: CertUtil [Options] -importPFX [CertificateStoreName] PFXFile [Modifiers]
dovescrywolf gave tip as a comment on article linked by Davide Inglima
It was was very useful for me on MacOS.
Open Termnal (bash console) and do below things:
$ pwd /Users/You/YourEclipseInstalationDirectory
$ cd Eclipse.app/Contents/MacOS/
$ echo "-Duser.name=Your Name" >> eclipse.ini
$ cat eclipse.ini
Close Terminal and start/open Eclipse again.
I think that main difference is whether you frequently need to insert or remove stuff from the top of the list.
With an array, if you remove something from the top of list than the complexity is o(n) because all of the indices of the array elements will have to shift.
With a linked list, it is o(1) because you need only create the node, reassign the head and assign the reference to next as the previous head.
When frequently inserting or removing at the end of the list, arrays are preferable because the complexity will be o(1), no reindexing is required, but for a linked list it will be o(n) because you need to go from the head to the last node.
I think that searching in both linked list and arrays will be o(log n) because you will be probably be using a binary search.
First set the isTranslucent property of navigationBar to false to get the desired colour. Then change the navigationBar colour like this:
@IBOutlet var NavigationBar: UINavigationBar!
NavigationBar.isTranslucent = false
NavigationBar.barTintColor = UIColor (red: 117/255, green: 23/255, blue: 49/255, alpha: 1.0)
For me it wasn't working even with hibernate.hbm2ddl.auto
set to update
. It turned out that the generated creation SQL was invalid, because one of my column names (user
) was an SQL keyword. This failed softly, and it wasn't obvious what was going on until I inspected the logs.
You can use the --ignore-table option. So you could do
mysqldump -u USERNAME -pPASSWORD DATABASE --ignore-table=DATABASE.table1 > database.sql
There is no whitespace after -p
(this is not a typo).
To ignore multiple tables, use this option multiple times, this is documented to work since at least version 5.0.
If you want an alternative way to ignore multiple tables you can use a script like this:
#!/bin/bash
PASSWORD=XXXXXX
HOST=XXXXXX
USER=XXXXXX
DATABASE=databasename
DB_FILE=dump.sql
EXCLUDED_TABLES=(
table1
table2
table3
table4
tableN
)
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done
echo "Dump structure"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE} > ${DB_FILE}
echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
Replace your "Save" button with an anchor link and set the new download
attribute dynamically. Works in Chrome and Firefox:
var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");
Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/
Here a compatibility table for download
attribute: http://caniuse.com/download
You can use index of columns:
data_set[,1:9] <- sapply(dataset[,1:9],as.character)
It is changed to : from PIL.Image import core as image
for new versions.
For a jQuery plugin try this
$.fn.removeClassLike = function(name) {
return this.removeClass(function(index, css) {
return (css.match(new RegExp('\\b(' + name + '\\S*)\\b', 'g')) || []).join(' ');
});
};
or this
$.fn.removeClassLike = function(name) {
var classes = this.attr('class');
if (classes) {
classes = classes.replace(new RegExp('\\b' + name + '\\S*\\s?', 'g'), '').trim();
classes ? this.attr('class', classes) : this.removeAttr('class');
}
return this;
};
Edit: The second approach should be a bit faster because that runs just one regex replace on the whole class string. The first (shorter) uses jQuery's own removeClass method which iterates trough all the existing classnames and tests them for the given regex one by one, so under the hood it does more steps for the same job. However in real life usage the difference is negligible.
tsc
requires a config file or .ts(x) files to compile.
To solve both of your issues, create a file called tsconfig.json
with the following contents:
{
"compilerOptions": {
"outFile": "../../built/local/tsc.js"
},
"exclude": [
"node_modules"
]
}
Also, modify your npm run with this
tsc --config /path/to/a/tsconfig.json
A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.
For example, If I do this:
Integer myInteger = null;
int n = myInteger.intValue();
The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.
What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]
RewriteCond %{REQUEST_URI} !^http://(www\.)?localhost/(.*)\.(gif|jpg|png|jpeg|mp4)$ [NC]
RewriteRule . - [F]
This is the implementation without using any Collection and with complexity order of n. Although the accepted solution is good enough and does not use Collection as well but it seems, it is not taking care of special characters.
import java.util.Arrays;
public class DuplicateCharactersInString {
public static void main(String[] args) {
String string = "check duplicate charcters in string";
string = string.toLowerCase();
char[] charAr = string.toCharArray();
Arrays.sort(charAr);
for (int i = 1; i < charAr.length;) {
int count = recursiveMethod(charAr, i, 1);
if (count > 1) {
System.out.println("'" + charAr[i] + "' comes " + count + " times");
i = i + count;
} else
i++;
}
}
public static int recursiveMethod(char[] charAr, int i, int count) {
if (ifEquals(charAr[i - 1], charAr[i])) {
count = count + recursiveMethod(charAr, ++i, count);
}
return count;
}
public static boolean ifEquals(char a, char b) {
return a == b;
}
}
Output :
' ' comes 4 times
'a' comes 2 times
'c' comes 5 times
'e' comes 3 times
'h' comes 2 times
'i' comes 3 times
'n' comes 2 times
'r' comes 3 times
's' comes 2 times
't' comes 3 times
Another option is:
when:
def response = mockMvc.perform(
get('/path/to/api')
.header("Content-Type", "application/json"))
then:
response.andExpect(status().isOk())
response.andReturn().getResponse().getContentAsString() == "what you expect"
As I did not had the mentioned option in my VS which is Visual Studio Enterprise 2017, I had to look for some other option.
Here is it what I've found:
Go to Tools -> Options -> Debugging tab(General) and uncheck "Enable JavaScript debugging for Asp.Net(Chrome and IE).
parseInt(number * 100) / 100;
worked for me.
I've had this problem before and the conclusion I've come to is that the only way to stop a video in IE is to remove it from the DOM.
dir /s/d/a:-d "folderpath*.*" > file.txt
And, lose the /s if you do not need files from subfolders
Expanding upon Gustavo Lima's answer. The same thing can be done without creating an entirely new list. The values in the list can be replaced with the differentials as the FOR
loop progresses.
def f_ClosestVal(v_List, v_Number):
"""Takes an unsorted LIST of INTs and RETURNS INDEX of value closest to an INT"""
for _index, i in enumerate(v_List):
v_List[_index] = abs(v_Number - i)
return v_List.index(min(v_List))
myList = [1, 88, 44, 4, 4, -2, 3]
v_Num = 5
print(f_ClosestVal(myList, v_Num)) ## Gives "3," the index of the first "4" in the list.
You can get all keys in the Request.Form and then compare and get your desired values.
Your method body will look like this: -
List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
if (key.StartsWith("List"))
{
listValues.Add(Convert.ToInt32(Request.Form[key]));
}
}
The consequence of this is that you may need a rather insane-looking query, e. g.,
SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID] AS lngRecordID
,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName] AS vcrSourceWorkbookName
,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName] AS vcrImportFileName
,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime] AS dtmLastWriteTime
,[dbo].[tblTimeSheetExportFiles].[lngNRecords] AS lngNRecords
,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk] AS lngSizeOnDisk
,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity] AS lngLastIdentity
,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
,MIN ( [tblTimeRecords].[dtmActivity_Date] ) AS dtmPeriodFirstWorkDate
,MAX ( [tblTimeRecords].[dtmActivity_Date] ) AS dtmPeriodLastWorkDate
,SUM ( [tblTimeRecords].[decMan_Hours_Actual] ) AS decHoursWorked
,SUM ( [tblTimeRecords].[decAdjusted_Hours] ) AS decHoursBilled
FROM [dbo].[tblTimeSheetExportFiles]
LEFT JOIN [dbo].[tblTimeRecords]
ON [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
GROUP BY [dbo].[tblTimeSheetExportFiles].[lngRecordID]
,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]
Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.
I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.
IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.
check out the documentation and the demo.
You can do this with the following:
int counter = 0;
String sql = "SELECT projectName,Owner " + "FROM Project WHERE Owner= ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, "");
ResultSet rs = prep.executeQuery();
while (rs.next()) {
counter++;
}
System.out.println(counter);
This will give you the no of rows where the column value is null or blank.
When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.
Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.
Apply SerializableAttribute
to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute
even if the class also implements the ISerializable
interface to control the serialization process.
All the public and private fields in a type that are marked by the SerializableAttribute
are serialized by default, unless the type implements the ISerializable
interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute
. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute
to that field.
See MSDN for more details.
Edit 1
Any reason to not mark something as serializable
When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.
Try converting your boolean to an integer?
echo (int)$bool_val;
The code creates an anonymous function, and then immediately runs it. Similar to:
var temp = function() {
// init part
}
temp();
The purpose of this construction is to create a scope for the code inside the function. You can declare varaibles and functions inside the scope, and those will be local to that scope. That way they don't clutter up the global scope, which minimizes the risk for conflicts with other scripts.
One option would be to use the onResume of your first activity.
@Override
public void onResume()
{ // After a pause OR at startup
super.onResume();
//Refresh your stuff here
}
Or you can start Activity for Result:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
In secondActivity if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
if you don't want to return data:
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
Now in your FirstActivity class write following code for onActivityResult()
method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
//Update List
}
if (resultCode == RESULT_CANCELED) {
//Do nothing?
}
}
}//onActivityResult
The error already says what you have to do. MD5 operates on bytes, so you have to encode Unicode string into bytes
, e.g. with line.encode('utf-8')
.
Update: text-overflow: ellipsis
is now supported as of Firefox 7 (released September 27th 2011). Yay! My original answer follows as a historical record.
Justin Maxwell has cross browser CSS solution. It does come with the downside however of not allowing the text to be selected in Firefox. Check out his guest post on Matt Snider's blog for the full details on how this works.
Note this technique also prevents updating the content of the node in JavaScript using the innerHTML
property in Firefox. See the end of this post for a workaround.
CSS
.ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
-moz-binding: url('assets/xml/ellipsis.xml#ellipsis');
}
ellipsis.xml
file contents
<?xml version="1.0"?>
<bindings
xmlns="http://www.mozilla.org/xbl"
xmlns:xbl="http://www.mozilla.org/xbl"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
<binding id="ellipsis">
<content>
<xul:window>
<xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
</xul:window>
</content>
</binding>
</bindings>
Updating node content
To update the content of a node in a way that works in Firefox use the following:
var replaceEllipsis(node, content) {
node.innerHTML = content;
// use your favorite framework to detect the gecko browser
if (YAHOO.env.ua.gecko) {
var pnode = node.parentNode,
newNode = node.cloneNode(true);
pnode.replaceChild(newNode, node);
}
};
See Matt Snider's post for an explanation of how this works.
A Simple program in java for arrays having unique elements:
import java.util.*;
public class ArrayPairSum {
public static void main(String[] args) {
int []a = {2,4,7,3,5,1,8,9,5};
sumPairs(a,10);
}
public static void sumPairs(int []input, int k){
Set<Integer> set = new HashSet<Integer>();
for(int i=0;i<input.length;i++){
if(set.contains(input[i]))
System.out.println(input[i] +", "+(k-input[i]));
else
set.add(k-input[i]);
}
}
}
It may be a little late for this question to be answered, but here is what I found.
I don't want to debate on the fact that nodes does that better than php or not, this is not the point.
The solution is : I haven't found any implementation of socket.io for PHP.
But there are some ways to implement WebSockets. There is this jQuery plugin allowing you to use Websockets while gracefully degrading for non-supporting browsers. On the PHP side, there is this class which seems to be the most widely used for PHP WS servers.
Add line break to ::after
or ::before
pseudo-element content
.yourclass:before {
content: 'text here first \A text here second';
white-space: pre;
}
What I did:
composer update --prefer-source vendor/library-name
It fetches the library again along with it's git repo
To answer the original question on how to get the index as an integer for the desired selection, the following will work :
df[df['A']==5].index.item()
Here a CSS animation fork of jezzipin's Solution, to seperate code from styling.
JS:
$(window).on("scroll touchmove", function () {
$('#header_nav').toggleClass('tiny', $(document).scrollTop() > 0);
});
CSS:
.header {
width:100%;
height:100px;
background: #26b;
color: #fff;
position:fixed;
top:0;
left:0;
transition: height 500ms, background 500ms;
}
.header.tiny {
height:40px;
background: #aaa;
}
http://jsfiddle.net/sinky/S8Fnq/
On scroll/touchmove the css class "tiny" is set to "#header_nav" if "$(document).scrollTop()" is greater than 0.
CSS transition attribute animates the "height" and "background" attribute nicely.
Steps I did:
Init cookies as being NOT http-only in server-side app.'s:
app.configure(function(){
//a bunch of stuff
app.use(express.cookieSession({secret: 'mySecret', store: store, cookie: cookieSettings}));```
Then in client-side services.jss I put ['ngCookies'] in like this:
angular.module('swrp', ['ngCookies']).//etc
Then in controller.js
, in my function UserLoginCtrl
, I have $cookies
in there with $scope
at the top like so:
function UserLoginCtrl($scope, $cookies, socket) {
Lastly, to get the value of a cookie inside the controller function I did:
var mySession = $cookies['connect.sess'];
Now you can send that back to the server from the client. Awesome. Wish they would've put this in the Angular.js documentation. I figured it out by just reading the actual code for angular-cookies.js directly.
Not strictly related to the question but received the error ReflectionException: Class config does not exist
I had added a new .env
variable with spaces in it. Running php artisan config:clear
told me that any .env
variable with spaces in it should be surrounded by "
s.
Did this and my application stated working again, no need for config clear as still in development on Laravel Homestead (5.4)
Here is the complete code that I've tested and absolutely does NOT give me a "address already in use" error. You can save this in a file and run the file from within the base directory of the HTML files you want to serve. Additionally, you could programmatically change directories prior to starting the server
import socket
import SimpleHTTPServer
import SocketServer
# import os # uncomment if you want to change directories within the program
PORT = 8000
# Absolutely essential! This ensures that socket resuse is setup BEFORE
# it is bound. Will avoid the TIME_WAIT issue
class MyTCPServer(SocketServer.TCPServer):
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = MyTCPServer(("", PORT), Handler)
# os.chdir("/My/Webpages/Live/here.html")
httpd.serve_forever()
# httpd.shutdown() # If you want to programmatically shut off the server
apt-get install php5-curl
/etc/init.d/apache2 restart
(php4-curl if it's php4)
One of the solution to this is if you have childviewcontroller So you simply presentviewcontroller on its parent by given
[self.parentViewController presentViewController:viewController animated:YES completion:nil];
And for dismiss use the same dismissview controller.
[self dismissViewControllerAnimated:YES completion:nil];
This is perfect solution works for me.
IMHO you can't compare SOAP and REST where those are two different things.
SOAP is a protocol and REST is a software architectural pattern. There is a lot of misconception in the internet for SOAP vs REST.
SOAP defines XML based message format that web service-enabled applications use to communicate each other over the internet. In order to do that the applications need prior knowledge of the message contract, datatypes, etc..
REST represents the state(as resources) of a server from an URL.It is stateless and clients should not have prior knowledge to interact with server beyond the understanding of hypermedia.
May be this can help, it's not exactly a background, but you get the simple idea
<style>
div {
float: left;
position: relative;
}
div img {
position: relative;
}
div div {
position: absolute;
top:0;
left:0;
}
</style>
<div>
<img src="http://www.planwallpaper.com/static/images/recycled_texture_background_by_sandeep_m-d6aeau9_PZ9chud.jpg" />
<div>Hello</div>
</div>
I don't know about javax.media.j3d, so I might be mistaken, but you usually want to investigate whether there is a memory leak. Well, as others note, if it was 64MB and you are doing something with 3d, maybe it's obviously too small...
But if I were you, I'll set up a profiler or visualvm, and let your application run for extended time (days, weeks...). Then look at the heap allocation history, and make sure it's not a memory leak.
If you use a profiler, like JProfiler or the one that comes with NetBeans IDE etc., you can see what object is being accumulating, and then track down what's going on.. Well, almost always something is incorrectly not removed from a collection...
The accepted answer is very useful and quite comprehensive. However, the OP states
I would like to see a simple example to write a callback function.
So here you go, from C++11 you have std::function
so there is no need for function pointers and similar stuff:
#include <functional>
#include <string>
#include <iostream>
void print_hashes(std::function<int (const std::string&)> hash_calculator) {
std::string strings_to_hash[] = {"you", "saved", "my", "day"};
for(auto s : strings_to_hash)
std::cout << s << ":" << hash_calculator(s) << std::endl;
}
int main() {
print_hashes( [](const std::string& str) { /** lambda expression */
int result = 0;
for (int i = 0; i < str.length(); i++)
result += pow(31, i) * str.at(i);
return result;
});
return 0;
}
This example is by the way somehow real, because you wish to call function print_hashes
with different implementations of hash functions, for this purpose I provided a simple one. It receives a string, returns an int (a hash value of the provided string), and all that you need to remember from the syntax part is std::function<int (const std::string&)>
which describes such function as an input argument of the function that will invoke it.
As far as I know, F11 or F12 doesn't work, and nor does Right Ctrl + F12.
Hit Left Ctrl + F12, or Home, or PageUp, (not NUMPAD 7 or NUMPAD 9 like the website says) to rotate the emulator.
To use the tuple you need to do the following, in the view change the model to:
@model Tuple<Person,Order>
to use @html methods you need to do the following i.e:
@Html.DisplayNameFor(tuple => tuple.Item1.PersonId)
or
@Html.ActionLink("Edit", "Edit", new { id=Model.Item1.Id }) |
Item1 indicates the first parameter passed to the Tuple method and you can use Item2 to access the second model and so on.
in your controller you need to create a variable of type Tuple and then pass it to the view:
public ActionResult Details(int id = 0)
{
Person person = db.Persons.Find(id);
if (person == null)
{
return HttpNotFound();
}
var tuple = new Tuple<Person, Order>(person,new Order());
return View(tuple);
}
Another example : Multiple models in a view
To my knowledge, Ejabberd (http://www.ejabberd.im/) is the parent, this is XMPP server which provide quite good features of open source, Whatsapp uses some modified version of this, facebook messaging also uses a modified version of this. Some more chat applications likes Samsung's ChatOn, Nimbuzz messenger all use ejabberd based ones and Erlang solutions also have modified version of this ejabberd which they claim to be highly scalable and well tested with more performance improvements and renamed as MongooseIM.
Ejabberd is the server which has most of the featured implemented when compared to other. Since it is build in Erlang it is highly scalable horizontally.
Something that is not explicitly said in the documentation or in the answers on this page (even though implied by @Naruto), is that FragmentPagerAdapter
will not update the Fragments if the data in the Fragment changes because it keeps the Fragment in memory.
So even if you have a limited number of Fragments to display, if you want to be able to refresh your fragments (say for example you re-run the query to update the listView in the Fragment), you need to use FragmentStatePagerAdapter.
My whole point here is that the number of Fragments and whether or not they are similar is not always the key aspect to consider. Whether or not your fragments are dynamic is also key.
Just follow the steps:
This is an incompatibility between Rails 2.3.8 and recent versions of RubyGems. Upgrade to the latest 2.3 version (2.3.11 as of today).
I'm pretty certain it is because the DbContext is not at all thread safe. So sharing the thing is never a good idea.
I've just had a look at the WebKit (Chrome, Safari …) source. Depending on the type of array, different sort methods are used:
Numeric arrays (or arrays of primitive type) are sorted using the C++ standard library function std::qsort
which implements some variation of quicksort (usually introsort).
Contiguous arrays of non-numeric type are stringified and sorted using mergesort, if available (to obtain a stable sorting) or qsort
if no merge sort is available.
For other types (non-contiguous arrays and presumably for associative arrays) WebKit uses either selection sort (which they call “min” sort) or, in some cases, it sorts via an AVL tree. Unfortunately, the documentation here is rather vague so you’d have to trace the code paths to actually see for which types which sort method is used.
And then there are gems like this comment:
// FIXME: Since we sort by string value, a fast algorithm might be to use a
// radix sort. That would be O(N) rather than O(N log N).
– Let’s just hope that whoever actually “fixes” this has a better understanding of asymptotic runtime than the writer of this comment, and realises that radix sort has a slightly more complex runtime description than simply O(N).
(Thanks to phsource for pointing out the error in the original answer.)
Maybe I'm misunderstanding, but if you want truly readonly Ids why not use an actual readonly field?
public class Person
{
public Person(int id)
{
m_id = id;
}
readonly int m_id;
public int Id { get { return m_id; } }
}
Since the Length
property of System.String
is an Int32
, I would guess that that the maximum length would be 2,147,483,647 chars (max Int32
size). If it allowed longer you couldn't check the Length since that would fail.
public decimal Total()
{
decimal decTotal=(datagridview1.DataSource as DataTable).Compute("Sum(FieldName)","");
return decTotal;
}
I'd recommend checking out json-stringify-safe from @isaacs-- it's used in NPM.
BTW- if you're not using Node.js, you can just copy and paste lines 4-27 from the relevant part of the source code.
To install:
$ npm install json-stringify-safe --save
To use:
// Require the thing
var stringify = require('json-stringify-safe');
// Take some nasty circular object
var theBigNasty = {
a: "foo",
b: theBigNasty
};
// Then clean it up a little bit
var sanitized = JSON.parse(stringify(theBigNasty));
This yields:
{
a: 'foo',
b: '[Circular]'
}
Note that, just like with the vanilla JSON.stringify function as @Rob W mentioned, you can also customize the sanitization behavior by passing in a "replacer" function as the second argument to
stringify()
. If you find yourself needing a simple example of how to do this, I just wrote a custom replacer which coerces errors, regexps, and functions into human-readable strings here.
Same question already answered here: How to list/download the recursive dependencies of a debian package?
try:
PACKAGES="wget unzip"
apt-get download $(apt-cache depends --recurse --no-recommends --no-suggests \
--no-conflicts --no-breaks --no-replaces --no-enhances \
--no-pre-depends ${PACKAGES} | grep "^\w")
<select>
<option value="" style="display:none;"></option>
<option value="0">aaaa</option>
<option value="1">bbbb</option>
</select>
The '-Wait' option seemed to block for me even though my process had finished.
I tried Adrian's solution and it works. But I used Wait-Process instead of relying on a side effect of retrieving the process handle.
So:
$proc = Start-Process $msbuild -PassThru
Wait-Process -InputObject $proc
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to
find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
Just to sum up!
In my case, I was using MySQL WorkBench and
ALTER TABLE table_name RENAME COLUMN old_name new_name varchar(50) not null;
// without TO and specify data type of that column
was enough to change the column name!
To refresh the component at regular intervals I found this the best method. In the ngOnInit method setTimeOut function
ngOnInit(): void {
setTimeout(() => { this.ngOnInit() }, 1000 * 10)
}
//10 is the number of seconds
Got to
gradle-wrapper.properties
Change the version of the below mentioned distribution (gradle-5.6.4-bin.zip)
distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-bin.zip
Python shouldn't crash when you call getdata(). The image might be corrupted or there is something wrong with your PIL installation. Try it with another image or post the image you are using.
This should break down the image the way you want:
from PIL import Image
im = Image.open('um_000000.png')
pixels = list(im.getdata())
width, height = im.size
pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]
When you create the colorbar
try using the fraction and/or shrink parameters.
From the documents:
fraction 0.15; fraction of original axes to use for colorbar
shrink 1.0; fraction by which to shrink the colorbar
If your project has Roslyn references and you are deploying it on an IIS server, you might get unwanted errors on the website as many hosting providers still have not upgraded their servers and hence do not support Roslyn.
To resolve this issue, you will need to remove the Roslyn compiler from the project template. Removing Roslyn shouldn't affect your code's functionality. It worked fine for me and some other projects (C# 4.5.2) on which I worked.
Do the following steps:
Remove from following Nuget Packages using command line shown below (or you can use GUI of Nuget Package manager by Right Clicking on Root Project Solution and removing them).
PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
PM> Uninstall-package Microsoft.Net.Compilers
Remove the following code from your Web.Config file and restart IIS. (Use this method only if step 1 doesn't solve your problem.)
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
For all intents and purposes, C++ supports this via lambdas:1
int main() {
auto f = []() { return 42; };
std::cout << "f() = " << f() << std::endl;
}
Here, f
is a lambda object that acts as a local function in main
. Captures can be specified to allow the function to access local objects.
Behind the scenes, f
is a function object (i.e. an object of a type that provides an operator()
). The function object type is created by the compiler based on the lambda.
1 since C++11
It depends on what you are after in the Dictionary
Models.TestModels obj = new Models.TestModels();
foreach (var keyValuPair in obj.sp)
{
// KeyValuePair<int, dynamic>
}
foreach (var key in obj.sp.Keys)
{
// Int
}
foreach (var value in obj.sp.Values)
{
// dynamic
}
While reading Quake 2 source code I came up with something like this:
double normals[][] = {
#include "normals.txt"
};
(more or less, I don't have the code handy to check it now).
Since then, a new world of creative use of the preprocessor opened in front of my eyes. I no longer include just headers, but entire chunks of code now and then (it improves reusability a lot) :-p
Thanks John Carmack! xD
You need to set the selected attribute of the correct option tag:
<option value="January" selected="selected">January</option>
Your PHP would look something like this:
<option value="January"<?=$row['month'] == 'January' ? ' selected="selected"' : '';?>>January</option>
I usually find it neater to create an array of values and loop through that to create a dropdown.
If you are dealing with calculation, there are laws on how you should calculate and what precision you should use. If you fail that you will be doing something illegal. The only real reason is that the bit representation of decimal cases are not precise. As Basil simply put, an example is the best explanation. Just to complement his example, here's what happens:
static void theDoubleProblem1() {
double d1 = 0.3;
double d2 = 0.2;
System.out.println("Double:\t 0,3 - 0,2 = " + (d1 - d2));
float f1 = 0.3f;
float f2 = 0.2f;
System.out.println("Float:\t 0,3 - 0,2 = " + (f1 - f2));
BigDecimal bd1 = new BigDecimal("0.3");
BigDecimal bd2 = new BigDecimal("0.2");
System.out.println("BigDec:\t 0,3 - 0,2 = " + (bd1.subtract(bd2)));
}
Output:
Double: 0,3 - 0,2 = 0.09999999999999998
Float: 0,3 - 0,2 = 0.10000001
BigDec: 0,3 - 0,2 = 0.1
Also we have that:
static void theDoubleProblem2() {
double d1 = 10;
double d2 = 3;
System.out.println("Double:\t 10 / 3 = " + (d1 / d2));
float f1 = 10f;
float f2 = 3f;
System.out.println("Float:\t 10 / 3 = " + (f1 / f2));
// Exception!
BigDecimal bd3 = new BigDecimal("10");
BigDecimal bd4 = new BigDecimal("3");
System.out.println("BigDec:\t 10 / 3 = " + (bd3.divide(bd4)));
}
Gives us the output:
Double: 10 / 3 = 3.3333333333333335
Float: 10 / 3 = 3.3333333
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion
But:
static void theDoubleProblem2() {
BigDecimal bd3 = new BigDecimal("10");
BigDecimal bd4 = new BigDecimal("3");
System.out.println("BigDec:\t 10 / 3 = " + (bd3.divide(bd4, 4, BigDecimal.ROUND_HALF_UP)));
}
Has the output:
BigDec: 10 / 3 = 3.3333
In case its useful or a better way:
str = str.replace(/(\s*,?\s*)*$/, "");
It will replace all following combination end of the string:
1. ,<no space>
2. ,<spaces>
3. , , , , ,
4. <spaces>
5. <spaces>,
6. <spaces>,<spaces>
The time difference b/w to time will be shown use this method.
private void HoursCalculator()
{
var t1 = txtfromtime.Text.Trim();
var t2 = txttotime.Text.Trim();
var Fromtime = t1.Substring(6);
var Totime = t2.Substring(6);
if (Fromtime == "M")
{
Fromtime = t1.Substring(5);
}
if (Totime == "M")
{
Totime = t2.Substring(5);
}
if (Fromtime=="PM" && Totime=="AM" )
{
var dt1 = DateTime.Parse("1900-01-01 " + txtfromtime.Text.Trim());
var dt2 = DateTime.Parse("1900-01-02 " + txttotime.Text.Trim());
var t = dt1.Subtract(dt2);
//int temp = Convert.ToInt32(t.Hours);
//temp = temp / 2;
lblHours.Text =t.Hours.ToString() + ":" + t.Minutes.ToString();
}
else if (Fromtime == "AM" && Totime == "PM")
{
var dt1 = DateTime.Parse("1900-01-01 " + txtfromtime.Text.Trim());
var dt2 = DateTime.Parse("1900-01-01 " + txttotime.Text.Trim());
TimeSpan t = (dt2.Subtract(dt1));
lblHours.Text = t.Hours.ToString() + ":" + t.Minutes.ToString();
}
else
{
var dt1 = DateTime.Parse("1900-01-01 " + txtfromtime.Text.Trim());
var dt2 = DateTime.Parse("1900-01-01 " + txttotime.Text.Trim());
TimeSpan t = (dt2.Subtract(dt1));
lblHours.Text = t.Hours.ToString() + ":" + t.Minutes.ToString();
}
}
use your field id's
var t1 captures a value of 4:00AM
check this code may be helpful to someone.
Use :set nowrap
.. works like a charm!
I found php-cgi on my server. And its on environment path so I was able to run from anywhere. I executed succesfuly file.php
in my bash script.
#!/bin/bash
php-cgi ../path/file.php
And the script returned this after php script was executed:
X-Powered-By: PHP/7.1.1 Content-type: text/html; charset=UTF-8
done!
By the way, check first if it works by checking the version issuing the command php-cgi -v
Do you want to find elements that contain "match", or that equal "match"?
This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2
):
//*[text()='match']
This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2
):
//*[normalize-space(text())='match']
This will find all elements that contain 'match' in the text node value (matches random2
and random3
):
//*[contains(text(),'match')]
This XPATH 2.0 solution uses the matches()
function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^
) or a word boundary (i.e. \W
) and terminated by the end of the string (i.e. $
) or a word boundary. The third parameter i
evaluates the regex pattern case-insensitive. (matches random2
)
//*[matches(text(),'(^|\W)match($|\W)','i')]
imgtag.group(0)
or imgtag.group()
. This returns the entire match as a string. You are not capturing anything else either.
Given MyObject
that has a DateTime
member with a getDateTime()
method, you can sort an ArrayList
that contains MyObject
elements by the DateTime
objects like this:
Collections.sort(myList, new Comparator<MyObject>() {
public int compare(MyObject o1, MyObject o2) {
return o1.getDateTime().lt(o2.getDateTime()) ? -1 : 1;
}
});
Checkout this wiki, specifically the section Restrictions on valid host names
Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, "en.wikipedia.org" is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.
The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9', and the hyphen ('-'). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.
This command helped me to solve the problem:
export DISPLAY=:0
First let's understand what big O, big Theta and big Omega are. They are all sets of functions.
Big O is giving upper asymptotic bound, while big Omega is giving a lower bound. Big Theta gives both.
Everything that is ?(f(n))
is also O(f(n))
, but not the other way around.
T(n)
is said to be in ?(f(n))
if it is both in O(f(n))
and in Omega(f(n))
.
In sets terminology, ?(f(n))
is the intersection of O(f(n))
and Omega(f(n))
For example, merge sort worst case is both O(n*log(n))
and Omega(n*log(n))
- and thus is also ?(n*log(n))
, but it is also O(n^2)
, since n^2
is asymptotically "bigger" than it. However, it is not ?(n^2)
, Since the algorithm is not Omega(n^2)
.
O(n)
is asymptotic upper bound. If T(n)
is O(f(n))
, it means that from a certain n0
, there is a constant C
such that T(n) <= C * f(n)
. On the other hand, big-Omega says there is a constant C2
such that T(n) >= C2 * f(n))
).
Not to be confused with worst, best and average cases analysis: all three (Omega, O, Theta) notation are not related to the best, worst and average cases analysis of algorithms. Each one of these can be applied to each analysis.
We usually use it to analyze complexity of algorithms (like the merge sort example above). When we say "Algorithm A is O(f(n))
", what we really mean is "The algorithms complexity under the worst1 case analysis is O(f(n))
" - meaning - it scales "similar" (or formally, not worse than) the function f(n)
.
Well, there are many reasons for it, but I believe the most important of them are:
To demonstrate this issue, have a look at the following graphs:
It is clear that f(n) = 2*n
is "worse" than f(n) = n
. But the difference is not quite as drastic as it is from the other function. We can see that f(n)=logn
quickly getting much lower than the other functions, and f(n) = n^2
is quickly getting much higher than the others.
So - because of the reasons above, we "ignore" the constant factors (2* in the graphs example), and take only the big-O notation.
In the above example, f(n)=n, f(n)=2*n
will both be in O(n)
and in Omega(n)
- and thus will also be in Theta(n)
.
On the other hand - f(n)=logn
will be in O(n)
(it is "better" than f(n)=n
), but will NOT be in Omega(n)
- and thus will also NOT be in Theta(n)
.
Symetrically, f(n)=n^2
will be in Omega(n)
, but NOT in O(n)
, and thus - is also NOT Theta(n)
.
1Usually, though not always. when the analysis class (worst, average and best) is missing, we really mean the worst case.
I had same problem and despite having jstl
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
I had to add 'standard' as well:
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
Also, as mentioned in previous post:
<script type="text/javascript">
function hide(){
document.getElementById('id').hidden = true;
}
function show(){
document.getElementById('id').hidden = false;
}
</script>
Here is how I did to download quickly with cURL (I'm not sure how many files it can download though) :
setlocal EnableDelayedExpansion
cd where\to\download
set STR=
for /f "skip=2 delims=" %%F in ('P:\curl -l -u user:password ftp://ftp.example.com/directory/anotherone/') do set STR=-O "ftp://ftp.example.com/directory/anotherone/%%F" !STR!
path\to\curl.exe -v -u user:password !STR!
Why skip=2 ?
To get ride of .
and ..
Why delims= ? To support names with spaces
This may be the easiest method
System.out.println("\"Hello\"")
You can use dict.pop
:
mydict.pop("key", None)
Note that if the second argument, i.e. None
is not given, KeyError
is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.
/proc/net/tcp -a list of open tcp sockets
/proc/net/udp -a list of open udp sockets
/proc/net/raw -a list all the 'raw' sockets
These are the files, use cat
command to view them. For example:
cat /proc/net/tcp
You can also use the lsof
command.
lsof is a command meaning "list open files", which is used in many Unix-like systems to report a list of all open files and the processes that opened them.
I solved this issue by installing the Nuget package: Microsoft ASP.NET Web API 2.2 Client Libraries. This in turn installed newtonsoft.json version 6.04
Lamba expression aren't included in c# 2.0
maybe you could refert to this post here on SO
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat()
function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.
In the introduction of Bootstrap it states which imports you need to add. https://getbootstrap.com/docs/4.0/getting-started/introduction/#quick-start
You have to add some scripts in order to get bootstrap fully working. It's important that you include them in this exact order. Popper.js is one of them:
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
String[] listOfFiles = getActivity().getFilesDir().list();
or
String[] listOfFiles = Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS).list();
Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your function here
}
Swift 3
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
// your function here
}
Swift 2
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
// your function here
})
If you already have pods which are recreated, think to delete all deployments first
kubectl delete -n *NAMESPACE deployment *DEPLOYMENT
Just replace the NAMSPACE and the DEPLOYMENT to corresponding ones, you can get all deployments information by the following command
kubectl get deployments --all-namespaces
There's now an EMPTY
constant and an empty
function.
import { Observable, empty, of } from 'rxjs';
var delay = empty().pipe(delay(1000));
var delay2 = EMPTY.pipe(delay(1000));
Observable.empty()
doesn't exist anymore.
I was frustrated to see that people were not showing how to go both ways or showing that things work on none trivial UTF8 strings. I found a post on codereview.stackexchange.com that has some code that works well. I used it to turn ancient runes into bytes, to test some crypo on the bytes, then convert things back into a string. The working code is on github here. I renamed the methods for clarity:
// https://codereview.stackexchange.com/a/3589/75693
function bytesToSring(bytes) {
var chars = [];
for(var i = 0, n = bytes.length; i < n;) {
chars.push(((bytes[i++] & 0xff) << 8) | (bytes[i++] & 0xff));
}
return String.fromCharCode.apply(null, chars);
}
// https://codereview.stackexchange.com/a/3589/75693
function stringToBytes(str) {
var bytes = [];
for(var i = 0, n = str.length; i < n; i++) {
var char = str.charCodeAt(i);
bytes.push(char >>> 8, char & 0xFF);
}
return bytes;
}
The unit test uses this UTF-8 string:
// http://kermitproject.org/utf8.html
// From the Anglo-Saxon Rune Poem (Rune version)
const secretUtf8 = `?????????????????????????????
?????????????????????????????????????????
?????????????????????????????????????`;
Note that the string length is only 117 characters but the byte length, when encoded, is 234.
If I uncomment the console.log lines I can see that the string that is decoded is the same string that was encoded (with the bytes passed through Shamir's secret sharing algorithm!):
<head>
<script>
function myFunction() {
var x;
var r = confirm("Do you want to clear data?");
if (r == true) {
x = "Your Data is Cleared";
window.location.href = "firstpage.php";
}
else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>
<p id="demo"></p>
</body>
</html>
This will redirect to new php page.
I had this issue when having a custom display in my terminal when creating a new git project (I have my branch display before the pathname e.g. :/current/path). All I needed to do was do my initial commit to my master branch to get this message to go away.
For others that have a similar problem but with live share.
In the visual studio installer there was a warning that live share was not installed correctly and a modification was pending, that would download live share again.
After completion of the modification the error was resolved.
The answer is correct, however the perl documentation on how to handle deadlocks is a bit sparse and perhaps confusing with PrintError, RaiseError and HandleError options. It seems that rather than going with HandleError, use on Print and Raise and then use something like Try:Tiny to wrap your code and check for errors. The below code gives an example where the db code is inside a while loop that will re-execute an errored sql statement every 3 seconds. The catch block gets $_ which is the specific err message. I pass this to a handler function "dbi_err_handler" which checks $_ against a host of errors and returns 1 if the code should continue (thereby breaking the loop) or 0 if its a deadlock and should be retried...
$sth = $dbh->prepare($strsql);
my $db_res=0;
while($db_res==0)
{
$db_res=1;
try{$sth->execute($param1,$param2);}
catch
{
print "caught $_ in insertion to hd_item_upc for upc $upc\n";
$db_res=dbi_err_handler($_);
if($db_res==0){sleep 3;}
}
}
dbi_err_handler should have at least the following:
sub dbi_err_handler
{
my($message) = @_;
if($message=~ m/DBD::mysql::st execute failed: Deadlock found when trying to get lock; try restarting transaction/)
{
$caught=1;
$retval=0; # we'll check this value and sleep/re-execute if necessary
}
return $retval;
}
You should include other errors you wish to handle and set $retval depending on whether you'd like to re-execute or continue..
Hope this helps someone -
To anyone reading this in 2017, this is how I've done something similar.
DELETE pets, pets_activities FROM pets inner join pets_activities
on pets_activities.id = pets.id WHERE pets.`order` > :order AND
pets.`pet_id` = :pet_id
Generally, to delete rows from multiple tables, the syntax I follow is given below. The solution is based on an assumption that there is some relation between the two tables.
DELETE table1, table2 FROM table1 inner join table2 on table2.id = table1.id
WHERE [conditions]
JObject implements IDictionary, so you can use it that way. For ex,
var cycleJson = JObject.Parse(@"{""name"":""john""}");
//add surname
cycleJson["surname"] = "doe";
//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
So the final json will be
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
You can also use dynamic
keyword
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });
In your controller, add,
public function create()
{
$items = array(
'itemlist' => DB::table('itemtable')->get()
);
return view('prices.create', $items);
}
And in your view, use
<select name="categories" id="categories" class="form-control">
@foreach($itemlist as $item)
<option value="{{ $item->id }}">{{ $item->name }}</option>
@endforeach
</select>
In select box, it will be like this,
<select>
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
...
</select>
In my case, resetting ADB didn't make a difference. I also needed to delete my existing virtual devices, which were pretty old, and create new ones.
For excellent code-readability, Fest Assertions has nice support for asserting lists
So in this case, something like:
Assertions.assertThat(returnedComponents).containsExactly("One", "Two", "Three");
Or make the expected list to an array, but I prefer the above approach because it's more clear.
Assertions.assertThat(returnedComponents).containsExactly(argumentComponents.toArray());
If you need to print some custom HTML, you can use this method:
ts:
let control_Print;
control_Print = document.getElementById('__printingFrame');
let doc = control_Print.contentWindow.document;
doc.open();
doc.write("<div style='color:red;'>I WANT TO PRINT THIS, NOT THE CURRENT HTML</div>");
doc.close();
control_Print = control_Print.contentWindow;
control_Print.focus();
control_Print.print();
html:
<iframe title="Lets print" id="__printingFrame" style="width: 0; height: 0; border: 0"></iframe>
Another possibility is that setting dataType: json
causes JQuery to send the Content-Type: application/json
header. This is considered a non-standard header by CORS, and requires a CORS preflight request. So a few things to try:
1) Try configuring your server to send the proper preflight responses. This will be in the form of additional headers like Access-Control-Allow-Methods
and Access-Control-Allow-Headers
.
2) Drop the dataType: json
setting. JQuery should request Content-Type: application/x-www-form-urlencoded
by default, but just to be sure, you can replace dataType: json
with contentType: 'application/x-www-form-urlencoded'
I received this error when I was parsing dict
with nested for
:
cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
for attr in cat:
print(cats[cat][attr])
Traceback:
Traceback (most recent call last):
File "<input>", line 3, in <module>
KeyError: 'K'
Because in second loop should be cats[cat]
instead just cat
(what is just a key)
So:
cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
for attr in cats[cat]:
print(cats[cat][attr])
Gives
black
10
white
8
All I had to do was load localhost:80/phpmyadmin
and then the browser figured it out. After that, localhost/phpmyadmin
worked.
Can I just ask about the long term need for this facility - is it for debuging purposes?
If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.
Just my opinion, but I prefer the debugger approach - for code and databases.
Meld can compare directories:
meld directory1 directory2
Just use the directories of the two git repos and you will get a nice graphical comparison:
When you click on one of the blue items, you can see what changed.
The problem with using querySelectorAll
and a for
loop is that it creates a whole new event handler for each element in the array.
Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target
to refer to the specific element which triggered the event:
document.body.addEventListener("click", function (event) {
if (event.target.classList.contains("delete")) {
var title = event.target.getAttribute("title");
if (!confirm("sure u want to delete " + title)) {
event.preventDefault();
}
}
});
In this example we only create one event handler which is attached to the body
element. Whenever an element inside the body
is clicked, the click
event bubbles up to our event handler.
Every public folder makes the permission to 755. Problem solved.
Temporary tablespaces are used for database sorting and joining operations and for storing global temporary tables. It may grow in size over a period of time and thus either we need to recreate temporary tablespace or shrink it to release the unused space.
Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.
Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.
The best documentation you'll find on the topic is the virtual host documentation in the apache manual.
There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.
The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost
line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost
entry for each port.
Assuming you're starting from scratch, this is much simpler than it may seem.
If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.
NameVirtualHost *:80
If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost
directive, and it will be removed in a future version.
Now your vhost definitions:
<VirtualHost *:80>
DocumentRoot "/home/user/site1/"
ServerName site1
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/home/user/site2/"
ServerName site2
</VirtualHost>
You can run as many sites as you want on the same port. The ServerName
being different is enough to tell Apache which vhost to use. Also, the ServerName
directive is always the domain/hostname and should never include a path.
If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81
These preferences appear to have changed since @alex-dima's answer.
Changing settings
From menu choose: File -> Preferences -> Settings -> User/Workspace Settings. Filter default settings to search
.
You can modify the search.exclude
setting (copy from default setting to your user or workspace settings). That will apply only to searches. Note that settings from files.exclude
will be automatically applied.
If the settings don't work:
Make sure you didn't turn the search exclusion off. In the search area, expand the "files to exclude" input box and make sure that the gear icon is selected.
You might also need to Clear Editor History (See: https://github.com/Microsoft/vscode/issues/6502).
Example settings
For example, I am developing an EmberJS application which saves thousands of files under the tmp directory.
If you select WORKSPACE SETTINGS
on the right side of the search field, the search exclusion will only be applied to this particular project. And a corresponding .vscode
folder will be added to the root folder containing settings.json
.
This is my example settings:
{
// ...
"search.exclude": {
"**/.git": true,
"**/node_modules": true,
"**/bower_components": true,
"**/tmp": true
},
// ...
}
Note: Include a ** at the beginning of any search exclusion to cover the search term over any folders and sub-folders.
Picture of search before updating settings:
Before updating the settings the search results are a mess.
Picture of search after updating settings:
After updating the settings the search results are exactly what I want.
I use Hibernate 5.2 and @Temporal
is not required anymore.
java.util.date, sql.date, time.LocalDate are stored into DB with appropriate datatype as Date/timestamp.
I received this error, which was caused by having two build definitions that pointed to the same source. The issue was that I used a static build directory in the Build Agent.
This forum post describes my issue and resolution exactly: http://social.msdn.microsoft.com/Forums/en-US/tfsbuild/thread/60a4138a-9b28-4c46-bdf4-f9775ce43c3e/
Use this Code in code behind
Div_Card.Style["background-image"] = Page.ResolveUrl(Session["Img_Path"].ToString());
Try this:
Select u.[username]
,u.[ip]
,q.[time_stamp]
From [users] As u
Inner Join (
Select [username]
,max(time_stamp) as [time_stamp]
From [users]
Group By [username]) As [q]
On u.username = q.username
And u.time_stamp = q.time_stamp
Yes there is such a built-in function: os.path.join
.
>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'
Use str.split([sep[, maxsplit]])
with no sep
or sep=None
:
From docs:
If
sep
is not specified or isNone
, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
Demo:
>>> myString.split()
['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs']
Use str.join
on the returned list to get this output:
>>> ' '.join(myString.split())
'I want to Remove all white spaces, new lines and tabs'
The API does not support that directly. You can use the for(int i..) loop and count the elements or use subLists(0, size - 1) and handle the last element explicitly:
if(x.isEmpty()) return;
int last = x.size() - 1;
for(Integer i : x.subList(0, last)) out.println(i);
out.println("last " + x.get(last));
This is only useful if it does not introduce redundancy. It performs better than the counting version (after the subList overhead is amortized). (Just in case you cared after the boxing anyway).
I would recommend the rename
command for this. Type ren /?
at the command line for more help.
header.php has the title tag set to <title>%TITLE%</title>;
the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later. then, you use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
For more reference, click PHP - how to change title of the page AFTER including header.php?
A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting *
your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.
The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID
.
Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT *
is regarded as bad practice in production code: explicitly named columns are much safer.
Readonly will not "grayout" the textbox and will still submit the value on a postback.
Richard's answer is correct. Alternatively you can also create a MappingJsonFactory
(in org.codehaus.jackson.map
) which knows where to find ObjectMapper
. The error you got was because the regular JsonFactory
(from core
package) has no dependency to ObjectMapper
(which is in the mapper
package).
But usually you just use ObjectMapper
and do not worry about JsonParser
or other low level components -- they will just be needed if you want to data-bind parts of stream, or do low-level handling.
You simply need to do a SUBSTR on the string in col3....
Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'),
(instr(col3, '|', instr(col3, 'Client Name') -
instr(col3, 'Client Name'))
),
'Client Name = ',
'')
from Table01
And yes, that is a bad DB design for the reasons stated in the original issue
The easiest method is really good but you don't get a standard Java project, i.e., the .java and .class files separated in different folders.
To get this very easily:
<Enter>
and that's it.So, yeah, all what you need, just comment line in INI file like zend_extension=xdebug.so
or similar.
Comments can be made by adding semicolon.
But, such kind of answer already added, and I'd like to share ready solution to switch Xdebug status.
I've made quick switcher for Xdebug. Maybe it would be useful for someone.
To write to a file:
import json
myfile.write(json.dumps(mydict))
To read from a file:
import json
mydict = json.loads(myfile.read())
myfile
is the file object for the file that you stored the dict in.
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=@fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("@Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +""
part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=@fName"
oCmd.Parameters.AddWithValue("@fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null
.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person>
.
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
This a single solution, in where your_field is a field that will set and new_value is a new value field, that can a function or a single value
foreach ($array as $key => $item) {
$item["your_field"] = "new_value";
$array[$key] = $item;
}
In your case new_value will be a date() function
This is straight from Bjarne Stroustrup's page:
If you so choose, you can still shoot yourself in the foot by inheriting constructors in a derived class in which you define new member variables needing initialization:
struct B1 {
B1(int) { }
};
struct D1 : B1 {
using B1::B1; // implicitly declares D1(int)
int x;
};
void test()
{
D1 d(6); // Oops: d.x is not initialized
D1 e; // error: D1 has no default constructor
}
var idList=new int[]{1, 2, 3, 4};
var friendsToUpdate = await Context.Friends.Where(f =>
idList.Contains(f.Id).ToListAsync();
foreach(var item in previousEReceipts)
{
item.msgSentBy = "1234";
}
You can use foreach to update each element that meets your condition.
Here is an example in a more generic way:
var itemsToUpdate = await Context.friends.Where(f => f.Id == <someCondition>).ToListAsync();
foreach(var item in itemsToUpdate)
{
item.property = updatedValue;
}
Context.SaveChanges()
In general you will most probably use async methods with await for db queries.
If you don't want to use setMaxResults()
on the Query
object then you could always revert back to using normal SQL.
to complete of Pit answer and for better perfromance : get all in one query and use NextResult method.
using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
{
sqlCon.Open();
var com = sqlCon.CreateCommand();
com.CommandText = "select * from BigTable;select @@ROWCOUNT;";
using (var reader = com.ExecuteReader())
{
while(reader.read()){
//iterate code
}
int totalRow = 0 ;
reader.NextResult(); //
if(reader.read()){
totalRow = (int)reader[0];
}
}
sqlCon.Close();
}
If your values are integers, and you use Python 2.7 or newer, you can use collections.Counter
instead of dict
. The most_common
method will give you all items, sorted by the value.
As everyone said above, you can easily delete a FK. However, I just noticed that it can be necessary to drop the KEY itself at some point. If you have any error message to create another index like the last one, I mean with the same name, it would be useful dropping everything related to that index.
ALTER TABLE your_table_with_fk
drop FOREIGN KEY name_of_your_fk_from_show_create_table_command_result,
drop KEY the_same_name_as_above
pip list
is a shell command. You should run it in your shell (bash/cmd), rather than invoke it from python interpreter.
pip
does not provide a stable API. The only supported way of calling it is via subprocess
, see docs and the code at the end of this answer.
However, if you want to just check if pip
exists locally, without running it, and you are running Linux, I would suggest that you use bash's which
command:
which pip
It should show you whether the command can be found in bash's PATH
/aliases, and if it does, what does it actually execute.
If running pip
is not an issue, you could just do:
python -m pip --version
If you really need to do it from a python script, you can always put the import statement into a try...except
block:
try:
import pip
except ImportError:
print("Pip not present.")
Or check what's the output of a pip --version
using subprocess
module:
subprocess.check_call([sys.executable, '-m', 'pip', '--version'])
The workaround is simple. Just use the Uri().ToString() method and percent-encode white-spaces, if any, afterwards.
string path = new Uri("C:\my example?.txt").ToString().Replace(" ", "%20");
properly returns file:///C:/my%20example?.txt
First of all go to the /home directorty then open invisible shell script with some text editor, ~/.bash_profile (macOS) or ~/.bashrc (linux)
go to the bottom, you would see something like this,
export LD_LIBRARY_PATH = /usr/local/lib
change this like that( remove blank point around the =
),
export LD_LIBRARY_PATH=/usr/local/lib
it should be useful.
In case that you're using a directive like me this is how it works when you need the two data way binding for example after updating an attribute in any model or collection:
angular.module('yourApp').directive('setSurveyInEditionMode', setSurveyInEditionMode)
function setSurveyInEditionMode() {
return {
restrict: 'A',
link: function(scope, element, $attributes) {
element.on('click', function(event){
event.stopPropagation();
// In order to work with stopPropagation and two data way binding
// if you don't use scope.$apply in my case the model is not updated in the view when I click on the element that has my directive
scope.$apply(function () {
scope.mySurvey.inEditionMode = true;
console.log('inside the directive')
});
});
}
}
}
Now, you can easily use it in any button, link, div, etc. like so:
<button set-survey-in-edition-mode >Edit survey</button>
select format(convert(float,@your_column),'0.0#########')
Advantage: This solution is irrespective of the source datatype (float, scientific, varchar, date etc)
String
is limited to 10 digits, bigInt
gets rid of decimal values
you can do like this :
public void selectDropDownValue(String ValueToSelect)
{
webelement findDropDownValue=driver.findElements(By.id("id1")) //this will find that dropdown
wait.until(ExpectedConditions.visibilityOf(findDropDownValue)); // wait till that dropdown appear
super.highlightElement(findDropDownValue); // highlight that dropdown
new Select(findDropDownValue).selectByValue(ValueToSelect); //select that option which u had passed as argument
}
OCR can be pretty CPU intensive, you might want to reconsider doing it on a smart phone.
That aside, to my knowledge the popular OCR libraries are Aspire and Tesseract. Neither are straight up Java, so you're not going to get a drop-in Android OCR library.
However, Tesseract is open source (GitHub hosted infact); so you can throw some time at porting the subset you need to Java. My understanding is its not insane C++, so depending on how badly you need OCR it might be worth the time.
So short answer: No.
Long answer: if you're willing to work for it.
Late answer, I know but I too wanted this so I could log the SQL. The following is short and meets my needs.
The following produces SQL you can copy/paste in SSMS (it replaces the parameters with the values properly). You can add more types but this meets all I use in this case.
private static void LogSQL(SqlCommand cmd)
{
string query = cmd.CommandText;
foreach (SqlParameter prm in cmd.Parameters)
{
switch (prm.SqlDbType)
{
case SqlDbType.Bit:
int boolToInt = (bool)prm.Value ? 1 : 0;
query = query.Replace(prm.ParameterName, string.Format("{0}", (bool)prm.Value ? 1 : 0));
break;
case SqlDbType.Int:
query = query.Replace(prm.ParameterName, string.Format("{0}", prm.Value));
break;
case SqlDbType.VarChar:
query = query.Replace(prm.ParameterName, string.Format("'{0}'", prm.Value));
break;
default:
query = query.Replace(prm.ParameterName, string.Format("'{0}'", prm.Value));
break;
}
}
// the following is my how I write to my log - your use will vary
logger.Debug("{0}", query);
return;
}
Now I can log the SQL just before I execute it:
LogSQL(queryCmd)
queryCmd.ExecuteNonQuery()
Try this:
public interface MyService {
//Code
}
@Component("One")
public class MyServiceOne implements MyService {
//Code
}
@Component("Two")
public class MyServiceTwo implements MyService {
//Code
}
You should set the 'interactive_timeout' and 'wait_timeout' properties in the mysql config file to the values you need.
You can use PowerPivot to work with files of up to 2GB, which will be enough for your needs.
In reference to your comment after Ian Henry's answer, I'm not quite 100% sure I understand what you are asking.
If it is about getting double quote marks added into a string, you can concatenate the double quotes into your string, for example:
String theFirst = "Java Programming";
String ROM = "\"" + theFirst + "\"";
Or, if you want to do it with one String variable, it would be:
String ROM = "Java Programming";
ROM = "\"" + ROM + "\"";
Of course, this actually replaces the original ROM, since Java Strings are immutable.
If you are wanting to do something like turn the variable name into a String, you can't do that in Java, AFAIK.
Some examples of middleware: CORBA, Remote Method Invocation (RMI),...
The examples mentioned above are all pieces of software allowing you to take care of communication between different processes (either running on the same machine or distributed over e.g. the internet).
Use the substring method of the String class :
String removeCurrency=amount.getText().toString().substring(3);
You can use subSequence , it's same as substr in C
Str.subSequence(int Start , int End)
If you only want it to iterate over your HashMap, no need for a list:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values()) {
System.out.println(s);
}
Of course, if you want to modify your map structurally (i.e. more than only changing the value for an existing key) while iterating, then you better use the "copy to ArrayList" method, since otherwise you'll get a ConcurrentModificationException. Or export as an array:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values().toArray(new String[]{})) {
System.out.println(s);
}
Use os.chdir
to change directory .
Use glob.glob
to generate a list of file names which end it '.bak'. The elements of the list are just strings.
Then you could use os.unlink
to remove the files. (PS. os.unlink
and os.remove
are synonyms for the same function.)
#!/usr/bin/env python
import glob
import os
directory='/path/to/dir'
os.chdir(directory)
files=glob.glob('*.bak')
for filename in files:
os.unlink(filename)
Use simple
ssh-keyscan hostname
to find if key(s) exists on both sites:
ssh-keyscan rc1.localdomain
[or@rc2 ~]$ ssh-keyscan rc1
# rc1 SSH-2.0-OpenSSH_5.3
rc1 ssh-rsa AAAAB3NzaC1yc2EAAAABI.......==
ssh-keyscan rc2.localdomain
[or@rc2 ~]$ ssh-keyscan rc2
# rac2 SSH-2.0-OpenSSH_5.3
rac2 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAys7kG6pNiC.......==
There are only 4 kinds:
NULL
for each value in the table on the right. This means that every row from the table on the left will appear at least once in the output. A "cross join" or "cartesian join" is simply an inner join for which no join conditions have been specified, resulting in all pairs of rows being output.
Thanks to RusselH for pointing out FULL joins, which I'd omitted.
If you prefer ByteBuffer
like @kalefranz, there is always the posibility to concatenate two byte[]
(or even more) in one line, like this:
byte[] c = ByteBuffer.allocate(a.length+b.length).put(a).put(b).array();
example:
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Beige
Replcae \n with ","
AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
Now append "(double-quote) at the start and end
"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
If your text contains blank lines in between you can use regular expression \n+ instead of \n
example:
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Beige
Replcae \n+ with "," (in regex mode)
AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
Now append "(double-quote) at the start and end
"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
s3_sync:
bucket: ansible-harshika
file_root: "{{ pathoftsfiles }}"
validate_certs: false
mode: push
key_prefix: "{{ folder }}"
here the variables are being used named as 'pathoftsfiles' and 'folder'. Now the value to this variable can be given by the below command
sudo ansible-playbook multiadd.yml --extra-vars "pathoftsfiles=/opt/lampp/htdocs/video/uploads/tsfiles/$2 folder=nitesh"
Note: Don't use the inverted commas while passing the values to the variable in the shell command
Based on Rubens' solution, you need to enable Delayed Expansion of env variables (type "help setlocal" or "help cmd") so that the var is correctly evaluated in the loop:
@echo off
setlocal enabledelayedexpansion
set myvar=the list:
for /r %%i In (*.sql) DO set myvar=!myvar! %%i,
echo %myvar%
Also consider the following restriction (MSDN):
The maximum individual environment variable size is 8192bytes.
I'm using XAMPP 1.6.7 on Windows 7. This article worked for me.
I added the following lines in the file httpd-vhosts.conf
at C:/xampp/apache/conf/extra
.
I had also uncommented the line # NameVirtualHost *:80
<VirtualHost mysite.dev:80>
DocumentRoot "C:/xampp/htdocs/mysite"
ServerName mysite.dev
ServerAlias mysite.dev
<Directory "C:/xampp/htdocs/mysite">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
After restarting the apache, it were still not working.
Then I had to follow the step 9 mentioned in the article by editing the file C:/Windows/System32/drivers/etc/hosts
.
# localhost name resolution is handled within DNS itself.
127.0.0.1 localhost
::1 localhost
127.0.0.1 mysite.dev
Then I got working http://mysite.dev
I know this is an old post, but figured I'd share my two cents. @Neji is correct in that you can use sessionStorage.getItem('label')
, and sessionStorage.setItem('label', 'value')
(although he had the setItem
parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:
var val = sessionStorage.myValue
in place of getItem
and
sessionStorage.myValue = 'value'
in place of setItem
.
Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:
sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object
The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject
all you get is [object Object], which doesn't help you too much.
Your code fails because you are executing a method (addOption) on the jQuery object (and this object does not support the method)
You can use the standard Javascript function like this:
$("#dropListBuilding")[0].options.add( new Option("My Text","My Value") )
For those looking to debug gradle dependencies in react-native
projects, the command is (executed from projectname/android
)
./gradlew app:dependencies --configuration compile
http://blogs.oracle.com/jmxetc/entry/troubleshooting_connection_problems_in_jconsole
If you are trying to access a server which is behind a NAT - you will most probably have to start your server with the option
-Djava.rmi.server.hostname=<public/NAT address>
so that the RMI stubs sent to the client contain the server's public address allowing it to be reached by the clients from the outside.
public String randomString(String chars, int length) {
Random rand = new Random();
StringBuilder buf = new StringBuilder();
for (int i=0; i<length; i++) {
buf.append(chars.charAt(rand.nextInt(chars.length())));
}
return buf.toString();
}
bootstrap-datepicker.js
var defaults = $.fn.datepicker.defaults
autoclose: true
Save and refresh your project and this should do.
Above answers gave good solutions using Javscript. Here is a simple jQuery solution:
$('#iframeId').contents().find('div')
The trick here is jQuery's .contents()
method, unlike .children()
which can only get HTML elements, .contents()
can get both text nodes and HTML elements. That's why one can get document contents of an iframe by using it.
Further reading about jQuery .contents()
: .contents()
Note that the iframe and page have to be on the same domain.
If double-clicking on it brings up WinRAR, you need to change the program you are running it with. You can right-click on it and click "Open with". Java should be listed in there.
However, you must first upgrade your Java version to be compatible with that JAR.
Even you don't need to measure the length of string. A ! operator can solve everything for you. Remember always: !(empty string) = true !(some string) = false
So you could write:
<input ng-model="somefield">
<span ng-show="!somefield">Sorry, the field is empty!</span>
<span ng-hide="!somefield">Thanks. Successfully validated!</span>
Since I don't see the jQuery
tag in the OP, here is a javascript only option :
document.addEventListener("DOMContentLoaded", function (event) {
var _selector = document.querySelector('input[name=myCheckbox]');
_selector.addEventListener('change', function (event) {
if (_selector.checked) {
// do something if checked
} else {
// do something else otherwise
}
});
});
See JSFIDDLE
Like stated in this question: Git: Create a branch from unstagged/uncommited changes on master: stash is not necessary.
Just use:
git checkout -b topic/newbranch
Any uncommitted work will be taken along to the new branch.
If you try to push you will get the following message
fatal: The current branch feature/NEWBRANCH has no upstream branch. To push the current branch and set the remote as upstream, use
git push --set-upstream origin feature/feature/NEWBRANCH
Just do as suggested to create the branch remotely:
git push --set-upstream origin feature/feature/NEWBRANCH
There are new features added. But, you will have to see if it is worth the upgrade. Some good improvements in Management Studio 2008 though, especially the intellisense for the Query Editor.
Use Visual Studio Setup project. Setup project can automatically include .NET framework setup in your installation package:
Here is my step-by-step for windows forms application:
Create setup project. You can use Setup Wizard.
Select project type.
Select output.
Hit Finish.
Open setup project properties.
Chose to include .NET framework.
Build setup project
Check output
Note: The Visual Studio Installer projects are no longer pre-packed with Visual Studio. However, in Visual Studio 2013 you can download them by using:
Tools > Extensions and Updates > Online (search) > Visual Studio Installer Projects
docker ps
will reveal the list of containers running on docker. Find the one running on your needed port and note down its PID.
Stop and remove that container using following commands:
docker stop PID
docker rm PID
Now run docker-compose up
and your services should run as you have freed the needed port.
The short answer is no: MySQL does not allow you to add a WHERE
clause to the TRUNCATE
statement. Here's MySQL's documentation about the TRUNCATE
statement.
But the good news is that you can (somewhat) work around this limitation.
Simple, safe, clean but slow solution using DELETE
First of all, if the table is small enough, simply use the DELETE
statement (it had to be mentioned):
1. LOCK TABLE my_table WRITE;
2. DELETE FROM my_table WHERE my_date<DATE_SUB(NOW(), INTERVAL 1 MONTH);
3. UNLOCK TABLES;
The LOCK
and UNLOCK
statements are not compulsory, but they will speed things up and avoid potential deadlocks.
Unfortunately, this will be very slow if your table is large... and since you are considering using the TRUNCATE
statement, I suppose it's because your table is large.
So here's one way to solve your problem using the TRUNCATE
statement:
Simple, fast, but unsafe solution using TRUNCATE
1. CREATE TABLE my_table_backup AS
SELECT * FROM my_table WHERE my_date>=DATE_SUB(NOW(), INTERVAL 1 MONTH);
2. TRUNCATE my_table;
3. LOCK TABLE my_table WRITE, my_table_backup WRITE;
4. INSERT INTO my_table SELECT * FROM my_table_backup;
5. UNLOCK TABLES;
6. DROP TABLE my_table_backup;
Unfortunately, this solution is a bit unsafe if other processes are inserting records in the table at the same time:
TRUNCATE
statement resets the AUTO-INCREMENT
counter to zero. So any record inserted between steps 2 and 3 will have an ID that will be lower than older IDs and that might even conflict with IDs inserted at step 4 (note that the AUTO-INCREMENT
counter will be back to it's proper value after step 4).Unfortunately, it is not possible to lock the table and truncate it. But we can (somehow) work around that limitation using RENAME
.
Half-simple, fast, safe but noisy solution using TRUNCATE
1. RENAME TABLE my_table TO my_table_work;
2. CREATE TABLE my_table_backup AS
SELECT * FROM my_table_work WHERE my_date>DATE_SUB(NOW(), INTERVAL 1 MONTH);
3. TRUNCATE my_table_work;
4. LOCK TABLE my_table_work WRITE, my_table_backup WRITE;
5. INSERT INTO my_table_work SELECT * FROM my_table_backup;
6. UNLOCK TABLES;
7. RENAME TABLE my_table_work TO my_table;
8. DROP TABLE my_table_backup;
This should be completely safe and quite fast. The only problem is that other processes will see table my_table
disappear for a few seconds. This might lead to errors being displayed in logs everywhere. So it's a safe solution, but it's "noisy".
Disclaimer: I am not a MySQL expert, so these solutions might actually be crappy. The only guarantee I can offer is that they work fine for me. If some expert can comment on these solutions, I would be grateful.
Destructing assignment is the best way to solve your problem.
var a = 1;
var b = 2;
[a, b] = [b, a];
console.log("After swap a =", a, " and b =", b);
_x000D_
THE CORRECT WAY IS :
UPDATE test1
INNER JOIN test2 ON (test1.id = test2.id)
SET test1.data = test2.data
If you made a merge on Github and are seeing the error below. You need to pull (fetch and commit) the changes from the remote server before it will recognize the merge on your local. After doing this, Git will allow you to delete the branch without giving you the error.
error: The branch 'x' is not fully merged. If you are sure you want to delete it, run 'git branch -D 'x'.
Use this command to trigger the notification center notification from the terminal.
osascript -e 'display notification "Lorem ipsum dolor sit amet" with title "Title"'
Static methods in python are called classmethods. Take a look at the following code
class MyClass:
def myInstanceMethod(self):
print 'output from an instance method'
@classmethod
def myStaticMethod(cls):
print 'output from a static method'
>>> MyClass.myInstanceMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method myInstanceMethod() must be called [...]
>>> MyClass.myStaticMethod()
output from a static method
Notice that when we call the method myInstanceMethod, we get an error. This is because it requires that method be called on an instance of this class. The method myStaticMethod is set as a classmethod using the decorator @classmethod.
Just for kicks and giggles, we could call myInstanceMethod on the class by passing in an instance of the class, like so:
>>> MyClass.myInstanceMethod(MyClass())
output from an instance method
When you are using the wordpress prepare line, the above solutions do not work. This is the solution I used:
$Table_Name = $wpdb->prefix.'tablename';
$SearchField = '%'. $YourVariable . '%';
$sql_query = $wpdb->prepare("SELECT * FROM $Table_Name WHERE ColumnName LIKE %s", $SearchField) ;
$rows = $wpdb->get_results($sql_query, ARRAY_A);