Rucksack is brilliant, but you don't necessarily have to resort to build tools like Gulp or Grunt etc.
I made a demo using CSS Custom Properties (CSS Variables) to easily control the min and max font sizes.
Like so:
* {
/* Calculation */
--diff: calc(var(--max-size) - var(--min-size));
--responsive: calc((var(--min-size) * 1px) + var(--diff) * ((100vw - 420px) / (1200 - 420))); /* Ranges from 421px to 1199px */
}
h1 {
--max-size: 50;
--min-size: 25;
font-size: var(--responsive);
}
h2 {
--max-size: 40;
--min-size: 20;
font-size: var(--responsive);
}
Swift 3.0
Create a ViewController with the UITableViewDelegate and UITableViewDataSource protocols. Then create a tableView inside it, declaring its style to be UITableViewStyle.grouped. This will fix the headers.
lazy var tableView: UITableView = {
let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
view.delegate = self
view.dataSource = self
view.separatorStyle = .none
return view
}()
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
The following code will load an image from a file image.png
and will display it as grayscale.
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
fname = 'image.png'
image = Image.open(fname).convert("L")
arr = np.asarray(image)
plt.imshow(arr, cmap='gray', vmin=0, vmax=255)
plt.show()
If you want to display the inverse grayscale, switch the cmap to cmap='gray_r'
.
Try this way:
<td><a href="..." style="display:block;"> </a></td>
Yes.
Use the special %0
variable to get the path to the current file.
Write %~n0
to get just the filename without the extension.
Write %~n0%~x0
to get the filename and extension.
Also possible to write %~nx0
to get the filename and extension.
Google Apps Script is javascript, you can use all the string methods...
var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }
You can find doc on many sites, this one for example.
you can use update from...
something like:
update shipment set.... from shipment inner join ProfilerTest.dbo.BookingDetails on ...
There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.
The usual way to change the user agent for Firefox is to set the variable "general.useragent.override"
in your Firefox profile. Note that this is independent from Selenium.
You can direct Selenium to use a profile different from the default one, like this:
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "whatever you want")
driver = webdriver.Firefox(profile)
With Chrome, what you want to do is use the user-agent
command line option. Again, this is not a Selenium thing. You can invoke Chrome at the command line with chrome --user-agent=foo
to set the agent to the value foo
.
With Selenium you set it like this:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=whatever you want")
driver = webdriver.Chrome(chrome_options=opts)
Both methods above were tested and found to work. I don't know about other browsers.
Selenium does not have methods to query the user agent from an instance of WebDriver
. Even in the case of Firefox, you cannot discover the default user agent by checking what general.useragent.override
would be if not set to a custom value. (This setting does not exist before it is set to some value.)
Once the browser is started, however, you can get the user agent by executing:
agent = driver.execute_script("return navigator.userAgent")
The agent
variable will contain the user agent.
Use empty()
. It checks for both empty strings and null.
if (!empty($_POST['user'])) {
// do stuff
}
From the manual:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Another possibility
if (list.Count(customer => customer.Firstname == "John") > 0) {
//bla
}
Related to your question, you may want to consider limiting the amount of RAM SQL Server has access to if you are using it in a shared environment, i.e., on a server that hosts more than just SQL Server:
This will help alleviate SQL Server from consuming all the server's RAM.
Be sure to check out the VS 2010 Beta that was just released. The new editor should have this.
No, objects don't have a built in identifier, though you can add one by modifying the object prototype. Here's an example of how you might do that:
(function() {
var id = 0;
function generateId() { return id++; };
Object.prototype.id = function() {
var newId = generateId();
this.id = function() { return newId; };
return newId;
};
})();
That said, in general modifying the object prototype is considered very bad practice. I would instead recommend that you manually assign an id to objects as needed or use a touch
function as others have suggested.
there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD')
and heredoc(<<<EOD)
strings
you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.
nowdoc strings will not expand variables just like single quotes.
ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
Simple. IE6 and above will happily center your table with "margin: 0 auto;" if only the page renders in "standards" mode. To make this happen you need a valid doctype declaration, such as
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
or
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
True, IE5.5 and below will still refuse to center the table but perhaps you can live with that, especially if the page is still functional with the table left aligned. I think by now users of IE5.5 and below are fairly used to some odd looking websites - but you still need to ensure that those visual glitches don't render your site unusable.
Happy coding!
EDIT: Sorry, I should perhaps point out that you do not have to have a "strict" doctype to get IE6 and up into "standards" rendering mode. I realised it might seem that way from the doctype examples I posted above. For example, this doctype declaration will of course work equally:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
You have $headers .= '...';
followed by $headers = '...';
; the second line is overwriting the first.
Just put the $headers .= "Bcc: $emailList\r\n";
say after the Content-type
line and it should be fine.
On a side note, the To
is generally required; mail servers might mark your message as spam otherwise.
$headers = "From: [email protected]\r\n" .
"X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";
Using the SVG from @ArnoTenkink as an data url combined with the accepted answer, this gives us the perfect solution for retina displays.
select.form-control:not([multiple]) {
border-radius: 0;
appearance: none;
background-position: right 50%;
background-repeat: no-repeat;
background-image: url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%20%3C%21DOCTYPE%20svg%20PUBLIC%20%22-//W3C//DTD%20SVG%201.1//EN%22%20%22http%3A//www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22%3E%20%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%2214px%22%20height%3D%2212px%22%20viewBox%3D%220%200%2014%2012%22%20enable-background%3D%22new%200%200%2014%2012%22%20xml%3Aspace%3D%22preserve%22%3E%20%3Cpolygon%20points%3D%223.862%2C7.931%200%2C4.069%207.725%2C4.069%20%22/%3E%3C/svg%3E);
padding: .5em;
padding-right: 1.5em
}
This will search and replace all non ASCII letters:
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");
By.CLASS_NAME was not yet mentioned:
from selenium.webdriver.common.by import By
driver.find_element(By.CLASS_NAME, "content")
This is the list of attributes which can be used as locators in By:
CLASS_NAME
CSS_SELECTOR
ID
LINK_TEXT
NAME
PARTIAL_LINK_TEXT
TAG_NAME
XPATH
This might be a use case for a context manager. Leaving aside allowances for Windows OS, here's my suggestion:
#!/usr/bin/env python3
# file: 'readchar.py'
"""
Implementation of a way to get a single character of input
without waiting for the user to hit <Enter>.
(OS is Linux, Ubuntu 14.04)
"""
import tty, sys, termios
class ReadChar():
def __enter__(self):
self.fd = sys.stdin.fileno()
self.old_settings = termios.tcgetattr(self.fd)
tty.setraw(sys.stdin.fileno())
return sys.stdin.read(1)
def __exit__(self, type, value, traceback):
termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)
def test():
while True:
with ReadChar() as rc:
char = rc
if ord(char) <= 32:
print("You entered character with ordinal {}."\
.format(ord(char)))
else:
print("You entered character '{}'."\
.format(char))
if char in "^C^D":
sys.exit()
if __name__ == "__main__":
test()
You can use literal quoting:
stmt := q'[insert into MY_TBL (Col) values('ER0002')]';
Documentation for literals can be found here.
Alternatively, you can use two quotes to denote a single quote:
stmt := 'insert into MY_TBL (Col) values(''ER0002'')';
The literal quoting mechanism with the Q syntax is more flexible and readable, IMO.
Please try that:
<script>
$(document).ready(function(){
var add = '<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td>';
add+= '<input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> ';
add+= '<input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> ';
add+= '<a href="javascript:void(0);" class="remCF">Remove</a></td></tr>';
$(".addCF").click(function(){ $("#customFields").append(add); });
$("#customFields").on('click','.remCF',function(){
var inx = $('.remCF').index(this);
$('tr').eq(inx+1).remove();
});
});
</script>
<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:colorPrimary">#00397F</item>
<item name="android:textColorPrimary">#22397F</item>
<item name="android:colorAccent">#00397F</item>
<item name="colorPrimaryDark">#22397F</item>
</style>
The color of the buttons and other text can also be changed using appcompat :
We can iterate the string array from both the ends: start and end, and swap at each iteration.
function reverse(str) {
let strArray = str.split("");
let start = 0;
let end = strArray.length - 1;
while(start <= end) {
let temp = strArray[start];
strArray[start] = strArray[end];
strArray[end] = temp;
start++;
end--;
}
return strArray.join("");
}
Although the number of operations have reduced, its time complexity is still O(n) as the number of operations still scale linearly with the size of input.
Ref: AlgoDaily
What about something like this :
cat texte.txt | sed -e 's/\s/,/g' > texte-new.txt
(Yes, with some useless catting and piping ; could also use < to read from the file directly, I suppose -- used cat first to output the content of the file, and only after, I added sed to my command-line)
EDIT : as @ghostdog74 pointed out in a comment, there's definitly no need for thet cat/pipe ; you can give the name of the file to sed :
sed -e 's/\s/,/g' texte.txt > texte-new.txt
If "texte.txt" is this way :
$ cat texte.txt
this is a text
in which I want to replace
spaces by commas
You'll get a "texte-new.txt" that'll look like this :
$ cat texte-new.txt
this,is,a,text
in,which,I,want,to,replace
spaces,by,commas
I wouldn't go just replacing the old file by the new one (could be done with sed -i, if I remember correctly ; and as @ghostdog74 said, this one would accept creating the backup on the fly) : keeping might be wise, as a security measure (even if it means having to rename it to something like "texte-backup.txt")
You are trying to sum up all the elements of 2-D Array
In Matlab use
Array_Sum = sum(sum(Array_Name));
ClickOnce applications DO reside in a subdirectory of C:\Documents & Settings. They don't have "clean" installation directories because the local files are essentially "temporarily" downloaded to allow the application to run on the local PC and execution of the application is controlled from the ClickOnce server that they are deployed on depending on publishing settings (Checking for updates, version requirements, etc).
@DavidG's answer is correct, but I would like to add that if you're building from the command line, the equivalent solution is to make sure that you're using the appropriate version of msbuild
(in this particular case, it needs to be version 15).
Run msbuild /?
to see which version you're using or where msbuild
to check which location the environment takes the executable from and update (or point to the right location of) the tools if necessary.
Download the latest MSBuild tool from here.
As of March 2016, I ran into this issue trying to POST json over https (from python requests, not that it matters).
The trick is to put "client_max_body_size 200M;" in at least two places http {}
and server {}
:
1. the http
directory
/etc/nginx/nginx.conf
2. the server
directory in your vhost.
/etc/nginx/sites-available/mysite.com
, for those who do not have vhosts, it's probably your nginx.conf or in the same directory as it.3. the location /
directory in the same place as 2.
/
, but if its not working at all, i'd recommend applying this to /
and then once its working be more specific.Remember - if you have SSL, that will require you to set the above for the SSL server
and location
too, wherever that may be (ideally the same as 2.). I found that if your client tries to upload on http, and you expect them to get 301'd to https, nginx will actually drop the connection before the redirect due to the file being too large for the http server, so it has to be in both.
Recent comments suggest that there is an issue with this on SSL with newer nginx versions, but i'm on 1.4.6 and everything is good :)
Although the question relates to Ubuntu, let me contribute by saying that I'm on Mac and my python
command defaults to Python 2.7.5. I have Python 3 as well, accessible via python3
, so knowing the pip package origin, I just downloaded it and issued sudo python3 setup.py install
against it and, surely enough, only Python 3 has now this module inside its site packages. Hope this helps a wandering Mac-stranger.
If you need to call the same method from both Activities why not then use a third object?
public class FirstActivity extends Activity
{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
}
// Utility.method() used somewhere in FirstActivity
}
public class Utility {
public static void method()
{
}
}
public class SecondActivity extends Activity
{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Utility.method();
}
}
Of course making it static depends on the use case.
Unfortunately, combining multiple entity contexts into a single named connection isn't possible. If you want to use named connection strings from a .config file to define your Entity Framework connections, they will each have to have a different name. By convention, that name is typically the name of the context:
<add name="ModEntity" connectionString="metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
<add name="Entity" connectionString="metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SOMESERVER;Initial Catalog=SOMECATALOG;Persist Security Info=True;User ID=Entity;Password=Entity;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
However, if you end up with namespace conflicts, you can use any name you want and simply pass the correct name to the context when it is generated:
var context = new Entity("EntityV2");
Obviously, this strategy works best if you are using either a factory or dependency injection to produce your contexts.
Another option would be to produce each context's entire connection string programmatically, and then pass the whole string in to the constructor (not just the name).
// Get "Data Source=SomeServer..."
var innerConnectionString = GetInnerConnectionStringFromMachinConfig();
// Build the Entity Framework connection string.
var connectionString = CreateEntityConnectionString("Entity", innerConnectionString);
var context = new EntityContext(connectionString);
How about something like this:
Type contextType = typeof(test_Entities);
string innerConnectionString = ConfigurationManager.ConnectionStrings["Inner"].ConnectionString;
string entConnection =
string.Format(
"metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string=\"{1}\"",
contextType.Name,
innerConnectionString);
object objContext = Activator.CreateInstance(contextType, entConnection);
return objContext as test_Entities;
... with the following in your machine.config:
<add name="Inner" connectionString="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
This way, you can use a single connection string for every context in every project on the machine.
one of the easy way to do that is use landa function without any problem like
userControl_Material1.simpleButton4.Click += (s, ee) =>
{
Save_mat(mat_global);
};
In Firefox you might have the text of the div in a child node (o_div.childNodes[0]
)
var range = document.createRange();
range.setStart(o_div.childNodes[0],last_caret_pos);
range.setEnd(o_div.childNodes[0],last_caret_pos);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
To put a sequence or another numpy array into a numpy array, Just change this line:
kOUT=np.zeros(N+1)
to:
kOUT=np.asarray([None]*(N+1))
Or:
kOUT=np.zeros((N+1), object)
You can wrap the text as well. PFB sample code:
CellStyle wrapCellStyle = new_workbook.createCellStyle();
wrapCellStyle.setWrapText(true);
I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)
I pulled this from the example code in your link:
IF !%1==! GOTO VIEWDATA
REM IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM PRINT LINE WITH STRING MATCH, THEN EXIT.
:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM SHOW ENTIRE FILE, 1 PAGE AT A TIME.
:EXIT0
!%1==!
is simply an idiomatic use of ==
intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The !
in this case is just a character placeholder. It could be anything. If %1
has content, then the equality will be false, if it does not you'll just be comparing !
to !
and it will be true.
!==!
is not an operator, so writing "asdf" !==! "fdas"
is pretty nonsensical.
The suggestion to use if not "asdf" == "fdas"
is definitely the way to go.
One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.
Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that Aleksei's answer covers.
I encountered this problem while upgrading from CXF 2.7.0 to 3.0.2. Here is what I did to resolve it:
Included the following in my pom.xml
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.0</version>
</dependency>
and added the following provider
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />
</jaxrs:providers>
you can also add inline css for adding image as a background as per below example
<div class="item active" style="background-image: url(../../foo.png);">
There are no events in JQuery to detect css changes.
Refer here: onHide() type event in jQuery
It is possible:
DOM L2 Events module defines mutation events; one of them - DOMAttrModified is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers.
Source: Event detect when css property changed using Jquery
Without events, you can use setInterval
function, like this:
var maxTime = 5000, // 5 seconds
startTime = Date.now();
var interval = setInterval(function () {
if ($('#element').is(':visible')) {
// visible, do something
clearInterval(interval);
} else {
// still hidden
if (Date.now() - startTime > maxTime) {
// hidden even after 'maxTime'. stop checking.
clearInterval(interval);
}
}
},
100 // 0.1 second (wait time between checks)
);
Note that using setInterval
this way, for keeping a watch, may affect your page's performance.
7th July 2018:
Since this answer is getting some visibility and up-votes recently, here is additional update on detecting css changes:
Mutation Events have been now replaced by the more performance friendly Mutation Observer.
The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification.
Refer: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
What you want is %.2f
, not 2%f
.
Also, you might want to replace your %d
with a %f
;)
#include <cstdio>
int main()
{
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;
}
This will output:
When this number: 94.945600 is assigned to 2 dp, it will be: 94.95
See here for a full description of the printf formatting options: printf
@Zugwait's answer is correct. req.param()
is deprecated. You should use req.params
, req.query
or req.body
.
But just to make it clearer:
req.params
will be populated with only the route values. That is, if you have a route like /users/:id
, you can access the id
either in req.params.id
or req.params['id']
.
req.query
and req.body
will be populated with all params, regardless of whether or not they are in the route. Of course, parameters in the query string will be available in req.query
and parameters in a post body will be available in req.body
.
So, answering your questions, as color
is not in the route, you should be able to get it using req.query.color
or req.query['color']
.
Late answer here, but if you search /etc/init.d/apache2
for 'reload', you'll find something like this:
do_reload() {
if apache_conftest; then
if ! pidofproc -p $PIDFILE "$DAEMON" > /dev/null 2>&1 ; then
APACHE2_INIT_MESSAGE="Apache2 is not running"
return 2
fi
$APACHE2CTL graceful > /dev/null 2>&1
return $?
else
APACHE2_INIT_MESSAGE="The apache2$DIR_SUFFIX configtest failed. Not doing anything."
return 2
fi
}
Basically, what the answers that suggest using init.d, systemctl, etc are invoking is a thin wrapper that says:
apachectl graceful
(swallowing the output, and forwarding the exit code)This suggests that @Aruman's answer is also correct, provided you are confident there are no errors in your configuration or have already run apachctl configtest
manually.
The apache documentation also supplies the same command for a graceful restart (apachectl -k graceful
), and some more color on the behavior thereof.
You should be using things like: KeyEvent.VK_UP instead of the actual code.
How are you wanting to refactor it? What is the goal of the refactoring?
Use a special catch block for the exception of the Response.End() method
{
...
context.Response.End(); //always throws an exception
}
catch (ThreadAbortException e)
{
//this is special for the Response.end exception
}
catch (Exception e)
{
context.Response.ContentType = "text/plain";
context.Response.Write(e.Message);
}
Or just remove the Response.End() if your building a filehandler
You could use Range.Rows
, Range.Columns
or Range.Cells
. Each of these collections contain Range
objects.
Here's how you could modify Dick's example so as to work with Rows
:
Sub LoopRange()
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("A1:A6")
For Each rCell In rRng.Rows
Debug.Print rCell.Address, rCell.Value
Next rCell
End Sub
And Columns
:
Sub LoopRange()
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("A1:A6")
For Each rCol In rRng.Columns
For Each rCell In rCol.Rows
Debug.Print rCell.Address, rCell.Value
Next rCell
Next rCol
End Sub
There are two ways for delete Database
You can refer to the GitHub page "Duplicating a repository"
It uses:
git clone --mirror
: to clone every references (commits, tags, branches)git push --mirror
: to push everythingThat would give:
git clone --mirror https://bitbucket.org/exampleuser/repository-to-mirror.git
# Make a bare mirrored clone of the repository
cd repository-to-mirror.git
git remote set-url --push origin https://github.com/exampleuser/mirrored
# Set the push location to your mirror
git push --mirror
As Noted in the comments by L S:
Import Code
feature from GitHub described by MarMass.I had the same problem as you. After a long time spent Googling, I found out my error was caused by multiple users that had added the same key in their accounts.
So, here is my solution: delete the wrong-user's ssh-key (I can do it because the wrong-user is also my account). If the wrong-user isn't your account, you may need to change your ssh-key, but I don't think this gonna happen.
And I think your problem may be caused by a mistyping error in your accounts name.
The extended configuration section in a previous response with
...
...
<rollingStyle value="Composite" />
...
...
listed works but I did not have to use
<staticLogFileName value="false" />
. I think the RollingAppender must (logically) ignore that setting since by definition the file gets rebuilt each day when the application restarts/reused. Perhaps it does matter for immediate rollover EVERY time the application starts.
C#: try this
Use some delimeter,like this:
If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform
property:
.myclass {
text-transform: lowercase;
}
See https://developer.mozilla.org/en/CSS/text-transform for more info.
However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.
>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:
sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used.
Not sure if this does all expected things, but you can do just like that:
>>> del mymodule
>>> import mymodule
Mine was more of a mistake, what happened was loop click(i guess) basically by clicking on the login the parent was also clicked which ended up causing Maximum call stack size exceeded.
$('.clickhere').click(function(){
$('.login').click();
});
<li class="clickhere">
<a href="#" class="login">login</a>
</li>
If you want to specifically have your local ip address open when running ng serve you can do the following:
npm install internal-ip-cli --save
ng serve --open --host $(./node_modules/.bin/internal-ip --ipv4)
Something you can try is using the bind method, I think this achieves what you were asking for. If nothing else, it's still very useful.
function doClick(elem, func) {
var diffElem = document.getElementById('some_element'); //could be the same or different element than the element in the doClick argument
diffElem.addEventListener('click', func.bind(diffElem, elem))
}
function clickEvent(elem, evt) {
console.log(this);
console.log(elem);
// 'this' and elem can be the same thing if the first parameter
// of the bind method is the element the event is being attached to from the argument passed to doClick
console.log(evt);
}
var elem = document.getElementById('elem_to_do_stuff_with');
doClick(elem, clickEvent);
You can minify all your scripts in page, including analytics.js
using:
Remember to minify the files before using it. Otherwise it will consume more processing time.
A swifty implementation:
extension UIScrollView {
func scrollToBottom(animated: Bool) {
if self.contentSize.height < self.bounds.size.height { return }
let bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.size.height)
self.setContentOffset(bottomOffset, animated: animated)
}
}
use it:
yourScrollview.scrollToBottom(animated: true)
You have to include the schema if isnt a public one
SELECT *
FROM <schema>."my_table"
Or you can change your default schema
SHOW search_path;
SET search_path TO my_schema;
Check your table schema here
SELECT *
FROM information_schema.columns
For example if a table is on the default schema public
both this will works ok
SELECT * FROM parroquias_region
SELECT * FROM public.parroquias_region
But sectors need specify the schema
SELECT * FROM map_update.sectores_point
This appears to be missing the providerName="System.Data.EntityClient"
bit. Sure you got the whole thing?
If you are averse to boost, you can use regular old operator>>
, along with std::noskipws
:
EDIT: updates after testing.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>
void split(const std::string& str, std::vector<std::string>& v) {
std::stringstream ss(str);
ss >> std::noskipws;
std::string field;
char ws_delim;
while(1) {
if( ss >> field )
v.push_back(field);
else if (ss.eof())
break;
else
v.push_back(std::string());
ss.clear();
ss >> ws_delim;
}
}
int main() {
std::vector<std::string> v;
split("hello world how are you", v);
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "-"));
std::cout << "\n";
}
First backup the database. Then drop any foreign key associated with the table. truncate the foreign key table.Truncate the current table. Remove the required primary keys. Use sqlyog or workbench or heidisql or dbeaver or phpmyadmin.
For all example below you need to import fs and path modules:
const fs = require('fs');
const path = require('path');
function readFiles(dir, processFile) {
// read directory
fs.readdir(dir, (error, fileNames) => {
if (error) throw error;
fileNames.forEach(filename => {
// get current file name
const name = path.parse(filename).name;
// get current file extension
const ext = path.parse(filename).ext;
// get current file path
const filepath = path.resolve(dir, filename);
// get information about the file
fs.stat(filepath, function(error, stat) {
if (error) throw error;
// check if the current path is a file or a folder
const isFile = stat.isFile();
// exclude folders
if (isFile) {
// callback, do something with the file
processFile(filepath, name, ext, stat);
}
});
});
});
}
Usage:
// use an absolute path to the folder where files are located
readFiles('absolute/path/to/directory/', (filepath, name, ext, stat) => {
console.log('file path:', filepath);
console.log('file name:', name);
console.log('file extension:', ext);
console.log('file information:', stat);
});
/**
* @description Read files synchronously from a folder, with natural sorting
* @param {String} dir Absolute path to directory
* @returns {Object[]} List of object, each object represent a file
* structured like so: `{ filepath, name, ext, stat }`
*/
function readFilesSync(dir) {
const files = [];
fs.readdirSync(dir).forEach(filename => {
const name = path.parse(filename).name;
const ext = path.parse(filename).ext;
const filepath = path.resolve(dir, filename);
const stat = fs.statSync(filepath);
const isFile = stat.isFile();
if (isFile) files.push({ filepath, name, ext, stat });
});
files.sort((a, b) => {
// natural sort alphanumeric strings
// https://stackoverflow.com/a/38641281
return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
});
return files;
}
Usage:
// return an array list of objects
// each object represent a file
const files = readFilesSync('absolute/path/to/directory/');
More info on promisify in this article.
const { promisify } = require('util');
const readdir_promise = promisify(fs.readdir);
const stat_promise = promisify(fs.stat);
function readFilesAsync(dir) {
return readdir_promise(dir, { encoding: 'utf8' })
.then(filenames => {
const files = getFiles(dir, filenames);
return Promise.all(files);
})
.catch(err => console.error(err));
}
function getFiles(dir, filenames) {
return filenames.map(filename => {
const name = path.parse(filename).name;
const ext = path.parse(filename).ext;
const filepath = path.resolve(dir, filename);
return stat({ name, ext, filepath });
});
}
function stat({ name, ext, filepath }) {
return stat_promise(filepath)
.then(stat => {
const isFile = stat.isFile();
if (isFile) return { name, ext, filepath, stat };
})
.catch(err => console.error(err));
}
Usage:
readFiles('absolute/path/to/directory/')
// return an array list of objects
// each object is a file
// with those properties: { name, ext, filepath, stat }
.then(files => console.log(files))
.catch(err => console.log(err));
Note: return undefined
for folders, if you want you can filter them out:
readFiles('absolute/path/to/directory/')
.then(files => files.filter(file => file !== undefined))
.catch(err => console.log(err));
.outer {_x000D_
overflow-y: auto;_x000D_
height: 300px;_x000D_
}_x000D_
_x000D_
.outer {_x000D_
width: 100%;_x000D_
-layout: fixed;_x000D_
}_x000D_
_x000D_
.outer th {_x000D_
text-align: left;_x000D_
top: 0;_x000D_
position: sticky;_x000D_
background-color: white;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
<title>MYCRUD</title>_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container-fluid col-md-11">_x000D_
<div class="row">_x000D_
_x000D_
<div class="col-lg-12">_x000D_
_x000D_
_x000D_
<div class="card-body">_x000D_
<div class="outer">_x000D_
_x000D_
<table class="table table-hover bg-light">_x000D_
<thead>_x000D_
<tr>_x000D_
<th scope="col">ID</th>_x000D_
<th scope="col">Marca</th>_x000D_
<th scope="col">Editar</th>_x000D_
<th scope="col">Eliminar</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
_x000D_
_x000D_
<tr>_x000D_
<td>4</td>_x000D_
<td>Toyota</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>Honda </td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>5</td>_x000D_
<td>Myo</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>6</td>_x000D_
<td>Acer</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>HP</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>8</td>_x000D_
<td>DELL</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>9</td>_x000D_
<td>LOGITECH</td>_x000D_
<td> <a class="btn btn-success" href="#">_x000D_
<i class="fa fa-edit"></i>_x000D_
</a>_x000D_
</td>_x000D_
<td> <a class="btn btn-danger" href="#">_x000D_
<i class="fa fa-trash"></i>_x000D_
</a>_x000D_
</td>_x000D_
</tr>_x000D_
_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Maybe you could try
List<Article> findAllByPublicationDate(Date publicationDate);
The detail could be checked in this article:
The answer from @aioobe is excellent. I just want to add another way for Java 8.
int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);
System.out.println(Arrays.deepToString(twoDim));
For me it's intuitive and easy to remember with Java 8 syntax.
Right click on the project in solution explorer or class view window --> "View" --> "View Class Diagram"
You should use HTML5 data attributes. You can create your own attributes and save different values in them.
<input style="display:none" id="__pageLoaded" value=""/>
$(document).ready(function () {
if ($("#__pageLoaded").val() != 1) {
$("#__pageLoaded").val(1);
} else {
shared.isBackLoad = true;
$("#__pageLoaded").val(1);
// Call any function that handles your back event
}
});
The above code worked for me. On mobile browsers, when the user clicked on the back button, we wanted to restore the page state as per his previous visit.
When using Python 2.4, try
inf = float("9e999")
nan = inf - inf
I am facing the issue when I was porting the simplejson to an embedded device which running the Python 2.4, float("9e999")
fixed it. Don't use inf = 9e999
, you need convert it from string.
-inf
gives the -Infinity
.
For XAMPP users, open php.ini
file located in C:/xampp/php
and remove the ;
from the beginning of extension=soap
. Then restart Apache and that's it!
see https://www.cybertec-postgresql.com/en/joining-data-from-multiple-postgres-databases/ [published 2017]
These days you also have the option to use https://prestodb.io/
You can run SQL on that PrestoDB node and it will distribute the SQL query as required. It can connect to the same node twice for different databases, or it might be connecting to different nodes on different hosts.
It does not support:
DELETE
ALTER TABLE
CREATE TABLE (CREATE TABLE AS is supported)
GRANT
REVOKE
SHOW GRANTS
SHOW ROLES
SHOW ROLE GRANTS
So you should only use it for SELECT and JOIN needs. Connect directly to each database for the above needs. (It looks like you can also INSERT or UPDATE which is nice)
Client applications connect to PrestoDB primarily using JDBC, but other types of connection are possible including a Tableu compatible web API
This is an open source tool governed by the Linux Foundation and Presto Foundation.
The founding members of the Presto Foundation are: Facebook, Uber, Twitter, and Alibaba.
The current members are: Facebook, Uber, Twitter, Alibaba, Alluxio, Ahana, Upsolver, and Intel.
via Is there a way to link someone to a YouTube Video in HD 1080p quality?
Yes there is:
https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720
options are:
default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;
As mentioned, you have to use the /embed/
or /v/
URL.
Note: Some copyrighted content doesn't support be played in this way
final int[][] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Produces:
1 2 3
4 5 6
7 8 9
I believe that throwing an exception is a better idea for your situation. An alternative will be the simulation method to return a tuple. The first item will be the status and the second one the result:
result = simulate(open("myfile"))
if not result[0]:
print "error parsing stream"
else:
ret= result[1]
Hi I'm also relatively new but I can give you basic help.
UPDATE 12.01.2016:
The bold line is the current branch.
You can also just double click a branch to use checkout.
And here some helpful links:
Probably you are looking for JavaScript™ for Acrobat® API Reference.
This reference should be the most complete. But, as @Orbling said, not all PDF viewers might support all of the API.
EDIT:
It turns out there are newer versions of the reference in Acrobat SDK (thanks to @jss).
Acrobat Developer Center contains links to different versions of documentation. Current version of JavaScript reference from Acrobat DC SDK is available there too.
You don't need to apply to_date()
to sysdate
. It is already there:
select 1
from dual
WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY');
If you are concerned about the time component on the date, then use trunc()
:
select 1
from dual
WHERE trunc(sysdate) BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND
TO_DATE('20/06/2014', 'DD/MM/YYYY');
You have to use a negative lookahead assertion.
(?!^ABC$)
You could for example use the following.
(?!^ABC$)(^.*$)
If this does not work in your editor, try this. It is tested to work in ruby and javascript:
^((?!ABC).)*$
ORDER BY column OFFSET 0 ROWS
Surprisingly makes it work, what a strange feature.
A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:
;WITH cte AS (
SELECT .....long select statement here....
)
SELECT * FROM
(
SELECT * FROM
( -- necessary to nest selects for union to work with where & order clauses
SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
) first
UNION ALL
SELECT * FROM
(
SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example
So we get all results ordered by MainCol
But the results with MainCol = 1
get ordered by ColX
And the results with MainCol = 0
get ordered by ColY
Under NT-style cmd.exe, you can loop through the lines of a text file with
FOR /F %i IN (file.txt) DO @echo %i
Type "help for" on the command prompt for more information. (don't know if that works in whatever "DOS" you are using)
No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:variable name="mapping">
<item key="1" v1="A" v2="B" />
<item key="2" v1="X" v2="Y" />
</xsl:variable>
<xsl:variable name="mappingNode"
select="document('')//xsl:variable[@name = 'mapping']" />
<xsl:template match="....">
<xsl:variable name="testVariable" select="'1'" />
<xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />
<xsl:variable name="variable1" select="$values/@v1" />
<xsl:variable name="variable2" select="$values/@v2" />
</xsl:template>
</xsl:stylesheet>
In fact, once you've got the values
variable, you may not even need separate variable1
and variable2
variables. You could just use $values/@v1
and $values/@v2
instead.
Use java.io.File.listFiles
Or
If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles
public String getDaySuffix(int inDay)
{
String s = String.valueOf(inDay);
if (s.endsWith("1"))
{
return "st";
}
else if (s.endsWith("2"))
{
return "nd";
}
else if (s.endsWith("3"))
{
return "rd";
}
else
{
return "th";
}
}
For anyone using FluentNHibernate (my version is 2.1.2), it's just as repetitive but this works:
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("users");
Id(x => x.Id).Column("id").GeneratedBy.SequenceIdentity("users_id_seq");
I don't know Sonar, but I suspect it's looking for a private constructor:
private FilePathHelper() {
// No-op; won't be called
}
Otherwise the Java compiler will provide a public parameterless constructor, which you really don't want.
(You should also make the class final, although other classes wouldn't be able to extend it anyway due to it only having a private constructor.)
Combining a couple of the previous answers, you could try start /b cmd /c foo.exe
.
For a trivial example, if you wanted to print out the versions of java/groovy/grails/gradle, you could do this in a batch file:
@start /b cmd /c java -version
@start /b cmd /c gradle -version
@start /b cmd /c groovy -version
@start /b cmd /c grails -version
If you have something like Process Explorer (Sysinternals), you will see a few child cmd.exe processes each with a java process (as per the above commands). The output will print to the screen in whatever order they finish.
start /b : Start application without creating a new window. The
application has ^C handling ignored. Unless the application
enables ^C processing, ^Break is the only way to interrupt
the application
cmd /c : Carries out the command specified by string and then terminates
var str = "\(INT_VALUE) , \(FLOAT_VALUE) , \(DOUBLE_VALUE), \(STRING_VALUE)"
You can use the following:
/// <summary>
/// Serializes an object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializableObject"></param>
/// <param name="fileName"></param>
public void SerializeObject<T>(T serializableObject, string fileName)
{
if (serializableObject == null) { return; }
try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
}
}
catch (Exception ex)
{
//Log exception here
}
}
/// <summary>
/// Deserializes an xml file into an object list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public T DeSerializeObject<T>(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return default(T); }
T objectOut = default(T);
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
string xmlString = xmlDocument.OuterXml;
using (StringReader read = new StringReader(xmlString))
{
Type outType = typeof(T);
XmlSerializer serializer = new XmlSerializer(outType);
using (XmlReader reader = new XmlTextReader(read))
{
objectOut = (T)serializer.Deserialize(reader);
}
}
}
catch (Exception ex)
{
//Log exception here
}
return objectOut;
}
The other answers are good, but if you have to worry about having NULL values, you may want this variant:
SELECT o.OrderId,
CASE WHEN ISNULL(o.NegotiatedPrice, o.SuggestedPrice) > ISNULL(o.SuggestedPrice, o.NegotiatedPrice)
THEN ISNULL(o.NegotiatedPrice, o.SuggestedPrice)
ELSE ISNULL(o.SuggestedPrice, o.NegotiatedPrice)
END
FROM Order o
The Problem is how you access row
Specifically row["waocs"]
and row["pool_number"]
of ocs[row["pool_number"]]=int(row["waocs"])
If you look up the official-documentation of fetchall()
you find.
The method fetches all (or all remaining) rows of a query result set and returns a list of tuples.
Therefore you have to access the values of rows with row[__integer__]
like row[0]
Get rid of the semicolon after WordGame
.
You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.
You can use find with a Predicate as follows:
list.Find(x => x.Id == IdToFind);
This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).
You can get a Developer_Key from here Get your Google Developer Key
{select as answered, if it answered.}
if you check this code reference, it states
Set DEVELOPER_KEY to the "API key" value from the "Access" tab of the Google APIs Console http://code.google.com/apis/console#access`
Wiki on step by step to get API Key & secret
http://code.garyjones.co.uk/google-developer-api-key
OR
If say, for instance, you have a web app which would require a API key then check this:
The Service application that you have created can be used by your Web apps such as PHP, Python, ..., etc.
Ubuntu, which is a Debian derivative, follows a very precise structure when installing packages. In other words, all software installed through the packaging tools, such as apt-get or synaptic, will put the stuff in the same locations. If you become familiar with these locations, you'll always know where to find your stuff.
As a short cut, you can always open a tool like synaptic, find the installed package, and inspect the "properties". Under properties, you'll see a list of all installed files. Again, you can expect these to always follow the Debian/Ubuntu conventions; these are highly ordered Linux distributions. IN short, binaries will be in /usr/bin, or some other location on your path ( try 'echo $PATH' on the command line to see the possible locations ). Configuration is always in a subdirectory of /etc. And the "home" is typically in /usr/lib or /usr/share.
For instance, according to http://www.mkyong.com/maven/how-to-install-maven-in-ubuntu/, maven is installed like:
The Apt-get installation will install all the required files in the following folder structure
/usr/bin/mvn
/usr/share/maven2/
/etc/maven2
P.S The Maven configuration is store in /etc/maven2
Note, it's not just apt-get that will do this, it's any .deb package installer.
For getting Method Name and Class Name try this:
public static void Call()
{
StackTrace stackTrace = new StackTrace();
var methodName = stackTrace.GetFrame(1).GetMethod();
var className = methodName.DeclaringType.Name.ToString();
Console.WriteLine(methodName.Name + "*****" + className );
}
You can use the transpose
function from the data.table
library. Simple and fast solution that keeps numeric
values as numeric
.
library(data.table)
# get data
data("mtcars")
# transpose
t_mtcars <- transpose(mtcars)
# get row and colnames in order
colnames(t_mtcars) <- rownames(mtcars)
rownames(t_mtcars) <- colnames(mtcars)
The question has already been answered, but if you are looking for a shortcut during development, including this at the top of your python script will save you some time but mostly let you forget about actually having to make the conversion.
import os #Used in Testing Script
os.system("pyuic4 -o outputFile.py inpuiFile.ui")
Yet another 3rd party lib not mentioned here is mxDateTime (predecessor of both python datetime
and 3rd party timeutil
) could be used for this task.
The aforementioned yearsago
would be:
from mx.DateTime import now, RelativeDateTime
def years_ago(years, from_date=None):
if from_date == None:
from_date = now()
return from_date-RelativeDateTime(years=years)
First parameter is expected to be a DateTime
instance.
To convert ordinary datetime
to DateTime
you could use this for 1 second precision):
def DT_from_dt_s(t):
return DT.DateTimeFromTicks(time.mktime(t.timetuple()))
or this for 1 microsecond precision:
def DT_from_dt_u(t):
return DT.DateTime(t.year, t.month, t.day, t.hour,
t.minute, t.second + t.microsecond * 1e-6)
And yes, adding the dependency for this single task in question would definitely be an overkill compared even with using timeutil (suggested by Rick Copeland).
You should just fix your code but just in case,
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
One could simply use \r
to keep everything in the same line while erasing what was previously on that line.
This is what i did.
End results :
use like this your inline css
<td width="178" rowspan="3" valign="top"
align="right" background="images/left.jpg"
style="background-repeat:background-position: right top;">
</td>
@jim mcnamara: try using parentheses for around NF
, i. e. $(NF-1)
and $(NF)
instead of $NF-1
and $NF
(works on Mac OS X 10.6.8 for FreeBSD awk
and gawk
).
echo '
1 2
2 3
one
one two three
' | gawk '{if (NF >= 2) print $(NF-1), $(NF);}'
# output:
# 1 2
# 2 3
# two three
String input = EditTextinput.getText().toString();
input = input.replace(" ", "");
Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim
:
input = input.trim();
Adding my two cents, based on a performance issue I observed.
If simple queries are getting parellelized unnecessarily, it can bring more problems than solving one. However, before adding MAXDOP into the query as "knee-jerk" fix, there are some server settings to check.
In Jeremiah Peschka - Five SQL Server Settings to Change, MAXDOP and "COST THRESHOLD FOR PARALLELISM" (CTFP
) are mentioned as important settings to check.
Note: Paul White mentioned max server memory
aslo as a setting to check, in a response to Performance problem after migration from SQL Server 2005 to 2012. A good kb article to read is Using large amounts of memory can result in an inefficient plan in SQL Server
Jonathan Kehayias - Tuning ‘cost threshold for parallelism’ from the Plan Cache helps to find out good value for CTFP
.
Why is cost threshold for parallelism ignored?
Aaron Bertrand - Six reasons you should be nervous about parallelism has a discussion about some scenario where MAXDOP is the solution.
Parallelism-Inhibiting Components are mentioned in Paul White - Forcing a Parallel Query Execution Plan
Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top
, padding-bottom
, padding-left
, and padding-right;
or padding: [top] [right] [bottom] [left];
).
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
The only option to actuall have this made pixel perfect is to create some transparent padding within the GIF itself. That way you can actually align it to the right of the LI and still have the background padding you are looking for.
The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)
Example
ALTER TABLE 0_value_addition_setup ADD UNIQUE (`value_code`)
find . > files_and_folders 2>&-
2>&-
closes (-
) the standard error file descriptor (2
) so all error messages are silenced.
1
if any 'Permission denied
' errors would otherwise be printedfind
:find . -type d \! \( -readable -executable \) -prune -print -o -print > files_and_folders
Pass extra options to find
that -prune
(prevent descending into) but still -print
any directory (-type
d
) that does not (\!
) have both -readable
and -executable
permissions, or (-o
) -print
any other file.
-readable
and -executable
options are GNU extensions, not part of the POSIX standardPermission denied
' on abnormal/corrupt files (e.g., see bug report affecting container-mounted filesystems using lxcfs
< v2.0.5)find
(GNU, OSX/BSD, etc){ LC_ALL=C find . 3>&2 2>&1 1>&3 > files_and_folders | grep -v 'Permission denied'; [ $? = 1 ]; } 3>&2 2>&1
Use a pipeline to pass the standard error stream to grep
, removing all lines containing the 'Permission denied'
string.
LC_ALL=C
sets the POSIX locale using an environment variable, 3>&2 2>&1 1>&3
and 3>&2 2>&1
duplicate file descriptors to pipe the standard-error stream to grep
, and [ $? = 1 ]
uses []
to invert the error code returned by grep
to approximate the original behavior of find
.
'Permission denied'
errors due to output redirection (e.g., if the files_and_folders
file itself is not writable)One more way:
>>> s='123456'
>>> ''.join([''.join(el) for el in zip(s[1::2], s[0::2])])
'214365'
When you have the expression:
a % b = c
It really means there exists an integer n
that makes c
as small as possible, but non-negative.
a - n*b = c
By hand, you can just subtract 2
(or add 2
if your number is negative) over and over until the end result is the smallest positive number possible:
3.14 % 2
= 3.14 - 1 * 2
= 1.14
Also, 3.14 % 2 * pi
is interpreted as (3.14 % 2) * pi
. I'm not sure if you meant to write 3.14 % (2 * pi)
(in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).
Similar to one of the answers above, I used
var sum = 0; //some value
let num = parseInt(val); //or just Number.parseInt
if(!isNaN(num)) {
sum += num;
}
This blogpost sheds some more light on this check if a string is numeric in Javascript | Typescript & ES6
The easiest way would be
Section = 'Sec_' + Section
But for efficiency, see: https://waymoot.org/home/python_string/
simplejson module is simply 1,5 times faster than json (On my computer, with simplejson 2.1.1 and Python 2.7 x86).
If you want, you can try the benchmark: http://abral.altervista.org/jsonpickle-bench.zip On my PC simplejson is faster than cPickle. I would like to know also your benchmarks!
Probably, as said Coady, the difference between simplejson and json is that simplejson includes _speedups.c. So, why don't python developers use simplejson?
you need to use backslash before ". like \"
From the doc here you can see that
A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.
and " (double quote) is a escacpe sequence
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence
She said "Hello!" to me.
you would write
System.out.println("She said \"Hello!\" to me.");
here's one way you can do it with awk
curl -sL 'http://twitter.com/users/username.json' | awk -F"," -v k="text" '{
gsub(/{|}/,"")
for(i=1;i<=NF;i++){
if ( $i ~ k ){
print $i
}
}
}'
If you're inserting text from a database or such (which one usually do), convert all "<br />
"'s to &vbCrLf. Works great for me :)
The command yum
that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum
command to fix that.
Your code could show this error this way:
import subprocess
try:
subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))
In Rails 6 there is a convenient way for resetting DB and planting seeds again:
rails db:seed:replant # Truncates tables of each database for current environment and loads the seeds
Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.
On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:
=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))
Hit OK then close the "Name Manager" window.
Now, in cell A1 enter the following:
=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))
This will return FQS for red and SM for yellow. For any other color the cell will remain blank.
***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).
Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html
Cheers.
::Edit::
The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).
Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:
=GET.CELL(63,Sheet1!B2)
If you want to suggest to the device (maybe a mobile phone) between alpha or numeric you can use <input type="number">
.
When creating AVD,
Now, after creating the AVD, you should see the google play icon .
You can use Lodash
const _ = require('lodash');
let firstObject = {'email' : '[email protected]};
let secondObject = { 'name' : { 'first':message.firstName } };
_.merge(firstObject, secondObject)
If the usage of something is part of the process of you making money, then it's generally considered a commercial use. If the purpose of the site is to, through some means or another, directly or indirectly, make you money, then it's probably commercial use.
If, on the other hand, something is merely incidental (not part of the process of production/working, but instead simply tacked on to the side), there are potential grounds for it not to be considered commercial use.
You can change this in the page load
.
My intention is that when the page comes to the load
function, switch the links (the current link in the required one)
You can use addEventListener
to pass this
to a JavaScript function.
HTML
<button id="button">Year</button>
JavaScript
(function () {
var btn = document.getElementById('button');
btn.addEventListener('click', function () {
Date('#year');
}, false);
})();
function Data(string)
{
$('.filter').removeClass('active');
$(this).parent().addClass('active') ;
}
This is for using a single directory for multiple projects. I use this technique for some closely related projects where I often need to pull changes from one project into another. It's similar to the orphaned branches idea but the branches don't need to be orphaned. Simply start all the projects from the same empty directory state.
Don't expect wonders from this solution. As I see it, you are always going to have annoyances with untracked files. Git doesn't really have a clue what to do with them and so if there are intermediate files generated by a compiler and ignored by your .gitignore file, it is likely that they will be left hanging some of the time if you try rapidly swapping between - for example - your software project and a PH.D thesis project.
However here is the plan. Start as you ought to start any git projects, by committing the empty repository, and then start all your projects from the same empty directory state. That way you are certain that the two lots of files are fairly independent. Also, give your branches a proper name and don't lazily just use "master". Your projects need to be separate so give them appropriate names.
Git commits (and hence tags and branches) basically store the state of a directory and its subdirectories and Git has no idea whether these are parts of the same or different projects so really there is no problem for git storing different projects in the same repository. The problem is then for you clearing up the untracked files from one project when using another, or separating the projects later.
cd some_empty_directory
git init
touch .gitignore
git add .gitignore
git commit -m empty
git tag EMPTY
Start your projects from empty.
git branch software EMPTY
git checkout software
echo "array board[8,8] of piece" > chess.prog
git add chess.prog
git commit -m "chess program"
whenever you like.
git branch thesis EMPTY
git checkout thesis
echo "the meaning of meaning" > philosophy_doctorate.txt
git add philosophy_doctorate.txt
git commit -m "Ph.D"
Go back and forwards between projects whenever you like. This example goes back to the chess software project.
git checkout software
echo "while not end_of_game do make_move()" >> chess.prog
git add chess.prog
git commit -m "improved chess program"
You will however be annoyed by untracked files when swapping between projects/branches.
touch untracked_software_file.prog
git checkout thesis
ls
philosophy_doctorate.txt untracked_software_file.prog
Sort of by definition, git doesn't really know what to do with untracked files and it's up to you to deal with them. You can stop untracked files from being carried around from one branch to another as follows.
git checkout EMPTY
ls
untracked_software_file.prog
rm -r *
(directory is now really empty, apart from the repository stuff!)
git checkout thesis
ls
philosophy_doctorate.txt
By ensuring that the directory was empty before checking out our new project we made sure there were no hanging untracked files from another project.
$ GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01T01:01:01' git commit -m empty
If the same dates are specified whenever committing an empty repository, then independently created empty repository commits can have the same SHA1 code. This allows two repositories to be created independently and then merged together into a single tree with a common root in one repository later.
# Create thesis repository.
# Merge existing chess repository branch into it
mkdir single_repo_for_thesis_and_chess
cd single_repo_for_thesis_and_chess
git init
touch .gitignore
git add .gitignore
GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01:T01:01:01' git commit -m empty
git tag EMPTY
echo "the meaning of meaning" > thesis.txt
git add thesis.txt
git commit -m "Wrote my PH.D"
git branch -m master thesis
# It's as simple as this ...
git remote add chess ../chessrepository/.git
git fetch chess chess:chess
It may also help if you keep your projects in subdirectories where possible, e.g. instead of having files
chess.prog
philosophy_doctorate.txt
have
chess/chess.prog
thesis/philosophy_doctorate.txt
In this case your untracked software file will be chess/untracked_software_file.prog
. When working in the thesis
directory you should not be disturbed by untracked chess program files, and you may find occasions when you can work happily without deleting untracked files from other projects.
Also, if you want to remove untracked files from other projects, it will be quicker (and less prone to error) to dump an unwanted directory than to remove unwanted files by selecting each of them.
So you might want to name your branches something like
project1/master
project1/featureABC
project2/master
project2/featureXYZ
Pretty late to the party, but I was struck here and got help from a friend. The thing was not to use PowerMock. This works with the latest version of Mockito.
Mockito comes with this org.mockito.internal.util.reflection.FieldSetter
.
What it basically does is helps you modify private fields using reflection.
This is how you use it:
@Mock
private Person mockedPerson;
private Test underTest;
// ...
@Test
public void testMethod() {
FieldSetter.setField(underTest, underTest.getClass().getDeclaredField("person"), mockedPerson);
// ...
verify(mockedPerson).someMethod();
}
This way you can pass a mock object and then verify it later.
Here is the reference.
To get just the value (without attribute names), use string()
:
string(//Parent[@id='1']/Children/child/@name)
The fn:string() fucntion will return the value of its argument as xs:string
. In case its argument is an attribute, it will therefore return the attribute's value as xs:string
.
replace the simple
$dom->loadHTML($html);
with the more robust ...
libxml_use_internal_errors(true);
if (!$DOM->loadHTML($page))
{
$errors="";
foreach (libxml_get_errors() as $error) {
$errors.=$error->message."<br/>";
}
libxml_clear_errors();
print "libxml errors:<br>$errors";
return;
}
I wanted to add a concrete example to accompany the other answers
You need to specify the name of the class that you want to test, so if you have the following project (this is a Play project):
You can test just the Login
tests by running the following command from the SBT console:
test:testOnly *LoginServiceSpec
If you are running the command from outside the SBT console, you would do the following:
sbt "test:testOnly *LoginServiceSpec"
The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:
c.sendall()
instead of c.send()
to prevent possible issues where you may not have sent the entire msg with one call (see docs).'b'
for bytes string: c.sendall(b'Thank you for connecting')
Best solution (should work w/both 2.x & 3.x):
output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))
Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
How about pass
?
To get a third order polynomial in x (x^3), you can do
lm(y ~ x + I(x^2) + I(x^3))
or
lm(y ~ poly(x, 3, raw=TRUE))
You could fit a 10th order polynomial and get a near-perfect fit, but should you?
EDIT: poly(x, 3) is probably a better choice (see @hadley below).
I brew installed it, and found it under /usr/local/apache-maven-3.3.3/conf
I got around a similar issue by setting defaultProps:
ComponentName.defaultProps = {
propName: ''
}
<select value="this.props.propName" ...
So now I avoid errors on compilation if my prop does not exist until mounting.
In your settings.py
add a root staticfiles directory:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
Create /static/images/favicon.ico
Add the favicon to your template(base.html):
{% load static %}
<link rel="shortcut icon" type="image/png" href="{% static 'images/favicon.ico' %}"/>
And create a url redirect in urls.py
because browsers look for a favicon in /favicon.ico
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
urlpatterns = [
...
path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('images/favicon.ico')))
]
For readonly/disabled and other attributes with true/false values
$(':submit').attr('disabled', function(_, attr){ return !attr});
I'd create a cte and do an inner join. It's not efficient but it's convenient
with table as (
SELECT DATE, STATUS, TITLE, ROW_NUMBER()
OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM TABLE)
select *
from table t
join select(
max(Row_Num) as Row_Num
,DATE
,STATUS
,TITLE
from table
group by date, status, title) t2
on t2.Row_Num = t.Row_Num and t2
and t2.date = t.date
and t2.title = t.title
You can use a form to do a POST to the same URL.
<form method="POST" name="refresh" id="refresh">
<input type="submit" value="Refresh" />
</form>
This gives you a button that refreshes the current page. It is a bit annoying because if the user presses the browser refresh button, they will get a do you want to resubmit the form
message.
I was trying use the audio players flutter package. Once I added it to pubspec.yaml and tried to import it to main.dart, I got the same error.
I tried to restart my IDE but that didn't help so i tried running
flutter packages pub cache repair
and it worked.
$('textarea').val();
textarea.value
would be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value
).
As others have said, some email programs will not read the css styles. If you already have a web email written up you can use the following tool from zurb to inline all of your styles:
http://zurb.com/ink/inliner.php
This comes in extremely handy when using templates like those mentioned above from mailchimp, campaign monitor, etc. as they, as you have found, will not work in some email programs. This tool leaves your style section for the mail programs that will read it and puts all the styles inline to get more universal readability in the format that you wanted.
Also worth remembering is that there are different types of MVPs as well. Fowler has broken the pattern into two - Passive View and Supervising Controller.
When using Passive View, your View typically implement a fine-grained interface with properties mapping more or less directly to the underlaying UI widget. For instance, you might have a ICustomerView with properties like Name and Address.
Your implementation might look something like this:
public class CustomerView : ICustomerView
{
public string Name
{
get { return txtName.Text; }
set { txtName.Text = value; }
}
}
Your Presenter class will talk to the model and "map" it to the view. This approach is called the "Passive View". The benefit is that the view is easy to test, and it is easier to move between UI platforms (Web, Windows/XAML, etc.). The disadvantage is that you can't leverage things like databinding (which is really powerful in frameworks like WPF and Silverlight).
The second flavor of MVP is the Supervising Controller. In that case your View might have a property called Customer, which then again is databound to the UI widgets. You don't have to think about synchronizing and micro-manage the view, and the Supervising Controller can step in and help when needed, for instance with compled interaction logic.
The third "flavor" of MVP (or someone would perhaps call it a separate pattern) is the Presentation Model (or sometimes referred to Model-View-ViewModel). Compared to the MVP you "merge" the M and the P into one class. You have your customer object which your UI widgets is data bound to, but you also have additional UI-spesific fields like "IsButtonEnabled", or "IsReadOnly", etc.
I think the best resource I've found to UI architecture is the series of blog posts done by Jeremy Miller over at The Build Your Own CAB Series Table of Contents. He covered all the flavors of MVP and showed C# code to implement them.
I have also blogged about the Model-View-ViewModel pattern in the context of Silverlight over at YouCard Re-visited: Implementing the ViewModel pattern.
This is my little debug environment:
error_reporting(-1);
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 0);
assert_options(ASSERT_QUIET_EVAL, 0);
assert_options(ASSERT_CALLBACK, 'assert_callcack');
set_error_handler('error_handler');
set_exception_handler('exception_handler');
register_shutdown_function('shutdown_handler');
function assert_callcack($file, $line, $message) {
throw new Customizable_Exception($message, null, $file, $line);
}
function error_handler($errno, $error, $file, $line, $vars) {
if ($errno === 0 || ($errno & error_reporting()) === 0) {
return;
}
throw new Customizable_Exception($error, $errno, $file, $line);
}
function exception_handler(Exception $e) {
// Do what ever!
echo '<pre>', print_r($e, true), '</pre>';
exit;
}
function shutdown_handler() {
try {
if (null !== $error = error_get_last()) {
throw new Customizable_Exception($error['message'], $error['type'], $error['file'], $error['line']);
}
} catch (Exception $e) {
exception_handler($e);
}
}
class Customizable_Exception extends Exception {
public function __construct($message = null, $code = null, $file = null, $line = null) {
if ($code === null) {
parent::__construct($message);
} else {
parent::__construct($message, $code);
}
if ($file !== null) {
$this->file = $file;
}
if ($line !== null) {
$this->line = $line;
}
}
}
Just use
for i in range(0, 5):
print i
to iterate through your data set and print each value.
For large data sets, you want to use xrange, which has a very similar signature, but works more effectively for larger data sets. http://docs.python.org/library/functions.html#xrange
You need to delete your old db folder and recreate new one. It will resolve your issue.
No one mentioned this but it helped me out and not many places on the net mention it.
Make sure your php.ini sets the following key:
upload_tmp_dir="/path/to/some/tmp/folder"
You'll need to check with your webhost if they want you to use an absolute server file path. You should be able to see other directory examples in your php.ini file to determine this. As soon as I set it I got values in my _FILES object.
Finally make sure that your tmp folder and wherever you are moving files to have the correct permissions so that they can be read and written to.
What I do in this scenario is create a table variable to hold the Ids.
Declare @Ids Table (id integer primary Key not null)
Insert @Ids(id) values (4),(7),(12),(22),(19)
-- (or call another table valued function to generate this table)
Then loop based on the rows in this table
Declare @Id Integer
While exists (Select * From @Ids)
Begin
Select @Id = Min(id) from @Ids
exec p_MyInnerProcedure @Id
Delete from @Ids Where id = @Id
End
or...
Declare @Id Integer = 0 -- assuming all Ids are > 0
While exists (Select * From @Ids
where id > @Id)
Begin
Select @Id = Min(id)
from @Ids Where id > @Id
exec p_MyInnerProcedure @Id
End
Either of above approaches is much faster than a cursor (declared against regular User Table(s)). Table-valued variables have a bad rep because when used improperly, (for very wide tables with large number of rows) they are not performant. But if you are using them only to hold a key value or a 4 byte integer, with a index (as in this case) they are extremely fast.
The problem sometimes occurs when there are errors in the project.
For instance, if your project is configured with a target of 3.2 but the 3.2 libraries are not available, you will not be able to change the version to 4.0!
The usual (perhaps brutal) solution I use is to create a new project with the correct target and copy src, res and manifest into the new project.
Update:
This seems to work:
I always run Android Tools | Fix Project Properties after making any changes to the build target.
There is no task to download dependencies; they are downloaded on demand. To learn how to manage dependencies with Gradle, see "Chapter 8. Dependency Management Basics" in the Gradle User Guide.
Use the SingleOrDefault() instead of FirstOrDefault().
Using Ramda:
import {addIndex, map} from 'ramda';
const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return 'X';
}, list);
As others have pointed out, you only need to close the outer wrapper.
BufferedReader reader = new BufferedReader(new FileReader(fileName));
There is a very slim chance that this could leak a file handle if the BufferedReader
constructor threw an exception (e.g. OutOfMemoryError
). If your app is in this state, how careful your clean up needs to be might depend on how critical it is that you don't deprive the OS of resources it might want to allocate to other programs.
The Closeable interface can be used if a wrapper constructor is likely to fail in Java 5 or 6:
Reader reader = new FileReader(fileName);
Closeable resource = reader;
try {
BufferedReader buffered = new BufferedReader(reader);
resource = buffered;
// TODO: input
} finally {
resource.close();
}
Java 7 code should use the try-with-resources pattern:
try (Reader reader = new FileReader(fileName);
BufferedReader buffered = new BufferedReader(reader)) {
// TODO: input
}
It's because you have:
def readTTable(fname):
try:
without a matching except
block after the try:
block. Every try
must have at least one matching except
.
See the Errors and Exceptions section of the Python tutorial.
i have this error when using "--ui tdd". remove this or using "--ui bdd" fix problem.
I had the same issue with npm install
.
After a lot of search, I found out that removing your .npmrc
file or its content (found at %USERPROFILE%/.npmrc
), will solve this issue. This worked for me.
Why not :
b = b.setScale(2, RoundingMode.HALF_UP);
You need to define border-width:1px
Your code should read:
$(this).css({"border-color": "#C1E0FF",
"border-width":"1px",
"border-style":"solid"});
You should ideally use a class and addClass/removeClass
$(this).addClass('borderClass');
$(this).removeClass('borderClass');
and in your CSS:
.borderClass{
border-color: #C1E0FF;
border-width:1px;
border-style: solid;
/** OR USE INLINE
border: 1px solid #C1E0FF;
**/
}
jsfiddle working example: http://jsfiddle.net/gorelative/tVbvF/\
jsfiddle with animate: http://jsfiddle.net/gorelative/j9Xxa/
This just gives you an example of how it could work, you should get the idea.. There are better ways of doing this most likely.. like using a toggle()
Not directly relevant, but often it's required to identify whether some token CAN be a url or not, not necessarily 100% correctly formed (ie, https part omitted and so on). I've read this post and did not find the solution, so I am posting my own here for the sake of completeness.
def get_domain_suffixes():
import requests
res=requests.get('https://publicsuffix.org/list/public_suffix_list.dat')
lst=set()
for line in res.text.split('\n'):
if not line.startswith('//'):
domains=line.split('.')
cand=domains[-1]
if cand:
lst.add('.'+cand)
return tuple(sorted(lst))
domain_suffixes=get_domain_suffixes()
def reminds_url(txt:str):
"""
>>> reminds_url('yandex.ru.com/somepath')
True
"""
ltext=txt.lower().split('/')[0]
return ltext.startswith(('http','www','ftp')) or ltext.endswith(domain_suffixes)
@@ -1,2 +3,4 @@
part of the diff
This part took me a while to understand, so I've created a minimal example.
The format is basically the same the diff -u
unified diff.
For instance:
diff -u <(seq 16) <(seq 16 | grep -Ev '^(2|3|14|15)$')
Here we removed lines 2, 3, 14 and 15. Output:
@@ -1,6 +1,4 @@
1
-2
-3
4
5
6
@@ -11,6 +9,4 @@
11
12
13
-14
-15
16
@@ -1,6 +1,4 @@
means:
-1,6
means that this piece of the first file starts at line 1 and shows a total of 6 lines. Therefore it shows lines 1 to 6.
1
2
3
4
5
6
-
means "old", as we usually invoke it as diff -u old new
.
+1,4
means that this piece of the second file starts at line 1 and shows a total of 4 lines. Therefore it shows lines 1 to 4.
+
means "new".
We only have 4 lines instead of 6 because 2 lines were removed! The new hunk is just:
1
4
5
6
@@ -11,6 +9,4 @@
for the second hunk is analogous:
on the old file, we have 6 lines, starting at line 11 of the old file:
11
12
13
14
15
16
on the new file, we have 4 lines, starting at line 9 of the new file:
11
12
13
16
Note that line 11
is the 9th line of the new file because we have already removed 2 lines on the previous hunk: 2 and 3.
Hunk header
Depending on your git version and configuration, you can also get a code line next to the @@
line, e.g. the func1() {
in:
@@ -4,7 +4,6 @@ func1() {
This can also be obtained with the -p
flag of plain diff
.
Example: old file:
func1() {
1;
2;
3;
4;
5;
6;
7;
8;
9;
}
If we remove line 6
, the diff shows:
@@ -4,7 +4,6 @@ func1() {
3;
4;
5;
- 6;
7;
8;
9;
Note that this is not the correct line for func1
: it skipped lines 1
and 2
.
This awesome feature often tells exactly to which function or class each hunk belongs, which is very useful to interpret the diff.
How the algorithm to choose the header works exactly is discussed at: Where does the excerpt in the git diff hunk header come from?
Date input = new Date(); // Imagine your Date here
LocalDate date = DateTimeUtils.toInstant(input)
.atZone(ZoneId.systemDefault())
.toLocalDate();
If you are using the backport of JSR 310, either you haven’t got a Date.toInstant()
method or it won’t give you the org.threeten.bp.Instant
that you need for you further conversion. Instead you need to use the DateTimeUtils
class that comes as part of the backport. The remainder of the conversion is the same, so so is the explanation.
If you want to execute that command, you should probably change:
PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'
to:
PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)
Syntax errors in the config file seem to cause problems. I found what the problem was by going to the directory and excuting this from the command line.
httpd -e info
This gave me the error
Syntax error on line 156 of D:/.../Apache Software Foundation/Apache2.2/conf/httpd.conf:
Invalid command 'PHPIniDir', perhaps misspelled or defined by a module not included in the server configuration
‘&&’ : - is a Logical AND operator produce a boolean value of true or false based on the logical relationship of its arguments.
For example: - Condition1 && Condition2
If Condition1 is false, then (Condition1 && Condition2) will always be false, that is the reason why this logical operator is also known as Short Circuit Operator because it does not evaluate another condition. If Condition1 is false , then there is no need to evaluate Condtiton2.
If Condition1 is true, then Condition2 is evaluated, if it is true then overall result will be true else it will be false.
‘&’ : - is a Bitwise AND Operator. It produces a one (1) in the output if both the input bits are one. Otherwise it produces zero (0).
For example:-
int a=12; // binary representation of 12 is 1100
int b=6; // binary representation of 6 is 0110
int c=(a & b); // binary representation of (12 & 6) is 0100
The value of c is 4.
for reference , refer this http://techno-terminal.blogspot.in/2015/11/difference-between-operator-and-operator.html
in regards to:
Take a look at the open source WordPress application. They have a very re-usable window they have created for displaying an "activity in progress" type display over top of whatever view your application is currently displaying.
note that if you do utilise this code you MUST provide ALL the sourcecode to your own application to any user that requests it. You need to be aware that they may decide to repackage your code and sell it on the store themselves. This is all provided for under the terms of the GNU General Public License (GPL).
If you don't want to be forced into opening your sourcecode then you cannot use anything from the wordpress iphone application including the, referenced activity progress window, without forcing the GPL to apply to your own.
You can get detail error by using responseText property.
$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error + "\nError detail: " + xhr.responseText);
}
});
Here is another one:
http://www.essentialobjects.com/Products/WebBrowser/Default.aspx
This one is also based on the latest Chrome engine but it's much easier to use than CEF. It's a single .NET dll that you can simply reference and use.
An empty field can be either an empty string or a NULL
.
To handle both, use:
email > ''
which can benefit from the range
access if you have lots of empty email record (both types) in your table.
A simple solution:
import webbrowser
webbrowser.open("C:\Users\Public\Music\Sample Music\Kalimba.mp3")
cheers...
Updated, Simple Solution
@media print {
body {
display: table;
table-layout: fixed;
padding-top: 2.5cm;
padding-bottom: 2.5cm;
height: auto;
}
}
Old Solution
Create section with each page, and use the below code to adjust margins, height and width.
If you are printing A4 size.
Then user
Size : 8.27in and 11.69 inches
@page Section1 {
size: 8.27in 11.69in;
margin: .5in .5in .5in .5in;
mso-header-margin: .5in;
mso-footer-margin: .5in;
mso-paper-source: 0;
}
div.Section1 {
page: Section1;
}
then create a div with all your content in it.
<div class="Section1">
type your content here...
</div>
What is currently happening is, that you have a certain set of files, which you have tried merging earlier, but they threw up merge conflicts.
Ideally, if one gets a merge conflict, he should resolve them manually, and commit the changes using git add file.name && git commit -m "removed merge conflicts"
.
Now, another user has updated the files in question on his repository, and has pushed his changes to the common upstream repo.
It so happens, that your merge conflicts from (probably) the last commit were not not resolved, so your files are not merged all right, and hence the U
(unmerged
) flag for the files.
So now, when you do a git pull
, git is throwing up the error, because you have some version of the file, which is not correctly resolved.
To resolve this, you will have to resolve the merge conflicts in question, and add and commit the changes, before you can do a git pull
.
# Note: commands below in format `CUURENT_WORKING_DIRECTORY $ command params`
Desktop $ cd test
First, let us create the repository structure
test $ mkdir repo && cd repo && git init && touch file && git add file && git commit -m "msg"
repo $ cd .. && git clone repo repo_clone && cd repo_clone
repo_clone $ echo "text2" >> file && git add file && git commit -m "msg" && cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone
Now we are in repo_clone, and if you do a git pull
, it will throw up conflicts
repo_clone $ git pull origin master
remote: Counting objects: 5, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From /home/anshulgoyal/Desktop/test/test/repo
* branch master -> FETCH_HEAD
24d5b2e..1a1aa70 master -> origin/master
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.
If we ignore the conflicts in the clone, and make more commits in the original repo now,
repo_clone $ cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone
And then we do a git pull
, we get
repo_clone $ git pull
U file
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm <file>'
as appropriate to mark resolution, or use 'git commit -a'.
Note that the file
now is in an unmerged state and if we do a git status
, we can clearly see the same:
repo_clone $ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
(use "git pull" to merge the remote branch into yours)
You have unmerged paths.
(fix conflicts and run "git commit")
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: file
So, to resolve this, we first need to resolve the merge conflict we ignored earlier
repo_clone $ vi file
and set its contents to
text2
text1
text1
and then add it and commit the changes
repo_clone $ git add file && git commit -m "resolved merge conflicts"
[master 39c3ba1] resolved merge conflicts
Easiest method:
From Command Line, use:
for %f in (*.*) do echo %f
From a Batch File (double up the % percent signs):
for %%f in (*.*) do echo %%f
From a Batch File with folder specified as 1st parameter:
for %%f in (%1\*.*) do echo %%f
i have changed my old path: jdbc:odbc:thin:@localhost:1521:orcl
to new : jdbc:oracle:thin:@//localhost:1521/orcl
and it worked for me.....hurrah!! image
We can use the new fs.promises API
const fs = require('fs').promises;
(async() => {
const stat = await fs.lstat('test.txt');
console.log(stat.isFile());
})().catch(console.error)
Here's how you would detect if a path is a file or a directory asynchronously, which is the recommended approach in node. using fs.lstat
const fs = require("fs");
let path = "/path/to/something";
fs.lstat(path, (err, stats) => {
if(err)
return console.log(err); //Handle error
console.log(`Is file: ${stats.isFile()}`);
console.log(`Is directory: ${stats.isDirectory()}`);
console.log(`Is symbolic link: ${stats.isSymbolicLink()}`);
console.log(`Is FIFO: ${stats.isFIFO()}`);
console.log(`Is socket: ${stats.isSocket()}`);
console.log(`Is character device: ${stats.isCharacterDevice()}`);
console.log(`Is block device: ${stats.isBlockDevice()}`);
});
Note when using the synchronous API:
When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.
try{
fs.lstatSync("/some/path").isDirectory()
}catch(e){
// Handle error
if(e.code == 'ENOENT'){
//no such file or directory
//do something
}else {
//do something else
}
}
preffered using the object tag
<object data='http://website.com/nameoffolder/documentname.pdf#toolbar=1'
type='application/pdf'
width='100%'
height='700px'>
note that you can change the width and height to any value you please visit http://www.w3schools.com/tags/tag_object.asp
I needed to do a little bit of testing myself of a button component. These tests work for me ;-)
import { shallow } from "enzyme";
import * as React from "react";
import Button from "../button.component";
describe("Button Component Tests", () => {
it("Renders correctly in DOM", () => {
shallow(
<Button text="Test" />
);
});
it("Expects to find button HTML element in the DOM", () => {
const wrapper = shallow(<Button text="test"/>)
expect(wrapper.find('button')).toHaveLength(1);
});
it("Expects to find button HTML element with className test in the DOM", () => {
const wrapper = shallow(<Button className="test" text="test"/>)
expect(wrapper.find('button.test')).toHaveLength(1);
});
it("Expects to run onClick function when button is pressed in the DOM", () => {
const mockCallBackClick = jest.fn();
const wrapper = shallow(<Button onClick={mockCallBackClick} className="test" text="test"/>);
wrapper.find('button').simulate('click');
expect(mockCallBackClick.mock.calls.length).toEqual(1);
});
});
On any linux system with the NVIDIA driver installed and loaded into the kernel, you can execute:
cat /proc/driver/nvidia/version
to get the version of the currently loaded NVIDIA kernel module, for example:
$ cat /proc/driver/nvidia/version
NVRM version: NVIDIA UNIX x86_64 Kernel Module 304.54 Sat Sep 29 00:05:49 PDT 2012
GCC version: gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
Both are shallow copies. CopyTo method is not a deep copy. Check the following code :
public class TestClass1
{
public string a = "test1";
}
public static void ArrayCopyClone()
{
TestClass1 tc1 = new TestClass1();
TestClass1 tc2 = new TestClass1();
TestClass1[] arrtest1 = { tc1, tc2 };
TestClass1[] arrtest2 = new TestClass1[arrtest1.Length];
TestClass1[] arrtest3 = new TestClass1[arrtest1.Length];
arrtest1.CopyTo(arrtest2, 0);
arrtest3 = arrtest1.Clone() as TestClass1[];
Console.WriteLine(arrtest1[0].a);
Console.WriteLine(arrtest2[0].a);
Console.WriteLine(arrtest3[0].a);
arrtest1[0].a = "new";
Console.WriteLine(arrtest1[0].a);
Console.WriteLine(arrtest2[0].a);
Console.WriteLine(arrtest3[0].a);
}
/* Output is
test1
test1
test1
new
new
new */
To replace commas with newline characters use this formula (assuming that the text to be altered is in cell A1):
=SUBSTITUTE(A1,",",CHAR(10))
You may have to then alter the row height to see all of the values in the cell
I've left a comment about the other part of your question
Edit: here's a screenshot of this working - I had to turn on "Wrap Text" in the "Format Cells" dialog.
Normally I would agree with Yaakov Ellis but in this special case there is another viable solution:
Use two tables:
Table: Item
Columns: ItemID, Title, Content
Indexes: ItemID
Table: Tag
Columns: ItemID, Title
Indexes: ItemId, Title
This has some major advantages:
First it makes development much simpler: in the three-table solution for insert and update of item
you have to lookup the Tag
table to see if there are already entries. Then you have to join them with new ones. This is no trivial task.
Then it makes queries simpler (and perhaps faster). There are three major database queries which you will do: Output all Tags
for one Item
, draw a Tag-Cloud and select all items for one Tag Title.
All Tags for one Item:
3-Table:
SELECT Tag.Title
FROM Tag
JOIN ItemTag ON Tag.TagID = ItemTag.TagID
WHERE ItemTag.ItemID = :id
2-Table:
SELECT Tag.Title
FROM Tag
WHERE Tag.ItemID = :id
Tag-Cloud:
3-Table:
SELECT Tag.Title, count(*)
FROM Tag
JOIN ItemTag ON Tag.TagID = ItemTag.TagID
GROUP BY Tag.Title
2-Table:
SELECT Tag.Title, count(*)
FROM Tag
GROUP BY Tag.Title
Items for one Tag:
3-Table:
SELECT Item.*
FROM Item
JOIN ItemTag ON Item.ItemID = ItemTag.ItemID
JOIN Tag ON ItemTag.TagID = Tag.TagID
WHERE Tag.Title = :title
2-Table:
SELECT Item.*
FROM Item
JOIN Tag ON Item.ItemID = Tag.ItemID
WHERE Tag.Title = :title
But there are some drawbacks, too: It could take more space in the database (which could lead to more disk operations which is slower) and it's not normalized which could lead to inconsistencies.
The size argument is not that strong because the very nature of tags is that they are normally pretty small so the size increase is not a large one. One could argue that the query for the tag title is much faster in a small table which contains each tag only once and this certainly is true. But taking in regard the savings for not having to join and the fact that you can build a good index on them could easily compensate for this. This of course depends heavily on the size of the database you are using.
The inconsistency argument is a little moot too. Tags are free text fields and there is no expected operation like 'rename all tags "foo" to "bar"'.
So tldr: I would go for the two-table solution. (In fact I'm going to. I found this article to see if there are valid arguments against it.)
Here is a flexible approach, it can be used in all cases, in particular:
dataframe
has been obtained from applying previous operations (e.g. not immediately opening a file, or creating a new data frame).First, un-factorize a string using the as.character
function, and, then, re-factorize with the as.factor
(or simply factor
) function:
fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
# Un-factorize (as.numeric can be use for numeric values)
# (as.vector can be use for objects - not tested)
fixed$Type <- as.character(fixed$Type)
fixed[1, ] <- c("lunch", 100)
# Re-factorize with the as.factor function or simple factor(fixed$Type)
fixed$Type <- as.factor(fixed$Type)
This snippet i have used in my application to encode the URL so may this can help you to do the same.
Function URLEncode(ByVal str As String) As String
Dim intLen As Integer
Dim x As Integer
Dim curChar As Long
Dim newStr As String
intLen = Len(str)
newStr = ""
For x = 1 To intLen
curChar = Asc(Mid$(str, x, 1))
If (curChar < 48 Or curChar > 57) And _
(curChar < 65 Or curChar > 90) And _
(curChar < 97 Or curChar > 122) Then
newStr = newStr & "%" & Hex(curChar)
Else
newStr = newStr & Chr(curChar)
End If
Next x
URLEncode = newStr
End Function
Download jquery.multiselect
Include the jquery.multiselect.js and jquery.multiselect.css files
<script src="jquery-ui-multiselect-widget-master/src/jquery.multiselect.js" type="text/javascript"></script>
<link rel="stylesheet" href="jquery-ui-multiselect-widget-master/jquery.multiselect.css" />
Populate your select input
Add the multiselect
$('#' + Field).multiselect({
checkAllText: "Your text for CheckAll",
uncheckAllText: "Your text for UncheckCheckAll",
noneSelectedText: "Your text for NoOptionHasBeenSelected",
selectedText: "You selected # of #" //The multiselect knows to display the second # as the total
});
You may change the style
ui-multiselect { //The button
background:#fff !important; //background-color wouldn't work here
text-align: right !important;
}
ui-multiselect-header { //The CheckAll/ UncheckAll line)
background: lightgray !important;
text-align: right !important;
}
ui-multiselect-menu { //The options
text-align: right !important;
}
If you want to repopulate the select, you must refresh it:
$('#' + Field).multiselect('refresh');
To get the selected values (comma separated):
var SelectedOptions = $('#' + Field).multiselect("getChecked").map(function () {
return this.value;
}).get();
To clear all selected values:
$('#' + Field).multiselect("uncheckAll");
No there is no method yet for NgFor using numbers instead collections, At the moment, *ngFor only accepts a collection as a parameter, but you could do this by following methods:
demo-number.pipe.ts:
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({name: 'demoNumber'})
export class DemoNumber implements PipeTransform {
transform(value, args:string[]) : any {
let res = [];
for (let i = 0; i < value; i++) {
res.push(i);
}
return res;
}
}
For newer versions you'll have to change your imports and remove args[]
parameter:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'demoNumber'})
export class DemoNumber implements PipeTransform {
transform(value) : any {
let res = [];
for (let i = 0; i < value; i++) {
res.push(i);
}
return res;
}
}
html:
<ul>
<li>Method First Using PIPE</li>
<li *ngFor='let key of 5 | demoNumber'>
{{key}}
</li>
</ul>
<ul>
<li>Method Second</li>
<li *ngFor='let key of [1,2]'>
{{key}}
</li>
</ul>
<ul>
<li>Method Third</li>
<li *ngFor='let loop2 of "0123".split("")'>{{loop2}}</li>
</ul>
<ul>
<li>Method Fourth</li>
<li *ngFor='let loop3 of counter(5) ;let i= index'>{{i}}</li>
</ul>
export class AppComponent {
demoNumber = 5 ;
counter = Array;
numberReturn(length){
return new Array(length);
}
}
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
Handles Button3.Click
Dim box = New AboutBox1()
box.Show()
End Sub
You need a space on either side of the !=
. Change your code to:
str="Hello World"
str2=" "
str3=""
if [ ! -z "$str" -a "$str" != " " ]; then
echo "Str is not null or space"
fi
if [ ! -z "$str2" -a "$str2" != " " ]; then
echo "Str2 is not null or space"
fi
if [ ! -z "$str3" -a "$str3" != " " ]; then
echo "Str3 is not null or space"
fi
If postgres was installed using homebrew, you can fix this by running:
brew link postgres
If we don't think this is a bug the team should fix, at lease MSDN should improve the document. The confusing really comes from the poor document of this. In MSDN, it explains the parameters name as,
Type: System.String
The name of the form field to return.
This just means the final html it generates will use that parameter as the name of the select input. But, it actually means more than that.
I guess the designer assumes that user will use a view model to display the dropdownlist, also will use post back to the same view model. But in a lot cases, we don't really follow that assumption.
Use the example above,
public class Person {
public int Id { get; set; }
public string Name { get; set; }
}
If we follow the assumption,we should define a view model for this dropdownlist related view
public class PersonsSelectViewModel{
public string SelectedPersonId,
public List<SelectListItem> Persons;
}
Because when post back, only the selected value will post back, so it assume it should post back to the model's property SelectedPersonId, which means Html.DropDownList's first parameter name should be 'SelectedPersonId'. So, the designer thinks that when display the model view in the view, the model's property SelectedPersonId should hold the default value of that dropdown list. Even thought your List<SelectListItem> Persons already set the Selected flag to indicate which one is selected/default, the tml.DropDownList will actually ignore that and rebuild it's own IEnumerable<SelectListItem> and set the default/selected item based on the name.
Here is the code from asp.net mvc
private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata,
string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool allowMultiple,
IDictionary<string, object> htmlAttributes)
{
...
bool usedViewData = false;
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = htmlHelper.GetSelectData(name);
usedViewData = true;
}
object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string));
// If we haven't already used ViewData to get the entire list of items then we need to
// use the ViewData-supplied value before using the parameter-supplied value.
if (defaultValue == null && !String.IsNullOrEmpty(name))
{
if (!usedViewData)
{
defaultValue = htmlHelper.ViewData.Eval(name);
}
else if (metadata != null)
{
defaultValue = metadata.Model;
}
}
if (defaultValue != null)
{
selectList = GetSelectListWithDefaultValue(selectList, defaultValue, allowMultiple);
}
...
return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
}
So, the code actually went further, it not only try to look up the name in the model, but also in the viewdata, as soon as it finds one, it will rebuild the selectList and ignore your original Selected.
The problem is, in a lot of cases, we don't really use it that way. we just want to throw in a selectList with one/multiple item(s) Selected set true.
Of course the solution is simple, use a name that not in the model nor in the viewdata. When it can not find a match, it will use the original selectList and the original Selected will take affect.
But i still think mvc should improve it by add one more condition
if ((defaultValue != null) && (!selectList.Any(i=>i.Selected)))
{
selectList = GetSelectListWithDefaultValue(selectList, defaultValue, allowMultiple);
}
Because, if the original selectList has already had one Selected, why would you ignore that?
Just my thoughts.
GetDateTimeFormats can parse DateTime to different formats. Example to "yyyy-MM-dd" format.
SomeDate.Value.GetDateTimeFormats()[5]
The following function will work in JDK version 1.5 and above.
public String getSimpleName()
In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click
on android:theme = "@style/AppTheme"
in the Android manifest file. It will open styles.xml
file where you can change the parent attribute of the style tag.
At parent=
in styles.xml
you can browse all available styles by using auto-complete inside the ""
. E.g. try parent="Theme."
with your cursor right after the .
and then pressing Ctrl + Space
.
You can also preview themes in the preview window in Android Studio.
It just doesn't make sense at all to be spending time invoking/defining routings. Even if you do need custom control, it's probably only for some of the time, and for the most bit you want to be able to just create a standard file structure of routings and have a module do it automatically.
Try Route Magic
As you scale your app, the routing invocations will start to form a giant heap of code that serves no purpose. You want to do just 2 lines of code to handle all the app.use
routing invocations with Route Magic like this:
const magic = require('express-routemagic')
magic.use(app, __dirname, '[your route directory]')
For those you want to handle manually, just don't use pass the directory to Magic.
Have a look at this solution I came up with
Positioned( child: SizedBox( child: CircularProgressIndicator(), width: 50, height: 50,), left: MediaQuery.of(context).size.width / 2 - 25);