How about:
<asp:HtmlIframe ID="yourIframe" runat="server" />
Is supported since .Net Framework 4.5
If you have Problems using this control, you might take a look here.
You can convert the value user provides to a double and store it again as nvarchar, with the aid of FormatProviders. CultureInfo is a typical FormatProvider. Assuming you know the culture you are operating,
System.Globalization.CultureInfo EnglishCulture = new System.Globalization.CultureInfo("en-EN");
System.Globalization.CultureInfo GermanCulture = new System.Globalization.CultureInfo("de-de");
will suffice to do the neccesary transformation, like;
double val;
if(double.TryParse("65,89875", System.Globalization.NumberStyles.Float, GermanCulture, out val))
{
string valInGermanFormat = val.ToString(GermanCulture);
string valInEnglishFormat = val.ToString(EnglishCulture);
}
if(double.TryParse("65.89875", System.Globalization.NumberStyles.Float, EnglishCulture, out val))
{
string valInGermanFormat = val.ToString(GermanCulture);
string valInEnglishFormat = val.ToString(EnglishCulture);
}
You need to annotate your Customer class with @Named or @Model annotation:
package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
private String email;
private String password;
}
or create/modify beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
They're not the same thing - UTF-8 is a particular way of encoding Unicode.
There are lots of different encodings you can choose from depending on your application and the data you intend to use. The most common are UTF-8, UTF-16 and UTF-32 s far as I know.
With bootstrap 3, just add the responsive and center classes:
<img class="img-responsive center-block" src="img/....jpg" alt="First slide">
This automatically does image resizing, and centers the picture.
Edit:
With bootstrap 4, just add the img-fluid
class
<img class="img-fluid" src="img/....jpg">
keycloak version: 4.6.0
For others come to here:
If you happen to put your docker command in a file, say run.sh
, check your line separator. In Linux, it should be LR
, otherwise you would get the same error.
There's actually a section in the OSTEP online textbook for an undergraduate course in operating systems which discusses exactly your question.
The relevant section is "Forgetting To Free Memory" in the Memory API chapter on page 6 which gives the following explanation:
In some cases, it may seem like not calling free() is reasonable. For example, your program is short-lived, and will soon exit; in this case, when the process dies, the OS will clean up all of its allocated pages and thus no memory leak will take place per se. While this certainly “works” (see the aside on page 7), it is probably a bad habit to develop, so be wary of choosing such a strategy
This excerpt is in the context of introducing the concept of virtual memory. Basically at this point in the book, the authors explain that one of the goals of an operating system is to "virtualize memory," that is, to let every program believe that it has access to a very large memory address space.
Behind the scenes, the operating system will translate "virtual addresses" the user sees to actual addresses pointing to physical memory.
However, sharing resources such as physical memory requires the operating system to keep track of what processes are using it. So if a process terminates, then it is within the capabilities and the design goals of the operating system to reclaim the process's memory so that it can redistribute and share the memory with other processes.
EDIT: The aside mentioned in the excerpt is copied below.
ASIDE: WHY NO MEMORY IS LEAKED ONCE YOUR PROCESS EXITS
When you write a short-lived program, you might allocate some space using
malloc()
. The program runs and is about to complete: is there need to callfree()
a bunch of times just before exiting? While it seems wrong not to, no memory will be "lost" in any real sense. The reason is simple: there are really two levels of memory management in the system. The first level of memory management is performed by the OS, which hands out memory to processes when they run, and takes it back when processes exit (or otherwise die). The second level of management is within each process, for example within the heap when you callmalloc()
andfree()
. Even if you fail to callfree()
(and thus leak memory in the heap), the operating system will reclaim all the memory of the process (including those pages for code, stack, and, as relevant here, heap) when the program is finished running. No matter what the state of your heap in your address space, the OS takes back all of those pages when the process dies, thus ensuring that no memory is lost despite the fact that you didn’t free it.Thus, for short-lived programs, leaking memory often does not cause any operational problems (though it may be considered poor form). When you write a long-running server (such as a web server or database management system, which never exit), leaked memory is a much bigger issue, and will eventually lead to a crash when the application runs out of memory. And of course, leaking memory is an even larger issue inside one particular program: the operating system itself. Showing us once again: those who write the kernel code have the toughest job of all...
from Page 7 of Memory API chapter of
Operating Systems: Three Easy Pieces
Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau Arpaci-Dusseau Books March, 2015 (Version 0.90)
In SQL server 2005 new datatypes were introduced: varchar(max)
and nvarchar(max)
They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar
and nvarchar
. Among these advantages are the ability to use string manipulation functions such as substring().
Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.
In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.
As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.
I managed to find network.http.connect.timeout for much older versions of Mozilla:
This preference was one of several added to allow low-level tweaking of the HTTP networking code. After a portion of the same code was significantly rewritten in 2001, the preference ceased to have any effect (as noted in all.js as early as September 2001).
Currently, the timeout is determined by the system-level connection establishment timeout. Adding a way to configure this value is considered low-priority.
It would seem that network.http.connect.timeout
hasn't done anything for some time.
I also saw references to network.http.request.timeout
, so I did a Google search. The results include lots of links to people recommending that others include it in about:config
in what appears to be a mistaken belief that it actually does something, since the same search turns up this about:config entries article:
Pref removed (unused). Previously: HTTP-specific network timeout. Default value is 120.
The same page includes additional information about network.http.connect.timeout
:
Pref removed (unused). Previously: determines how long to wait for a response until registering a timeout. Default value is 30.
Disclaimer: The information on the MozillaZine Knowledge Base may be incorrect, incomplete or out-of-date.
You can use
git rm -r --cached -- "path/to/directory"
to stage a deleted directory.
I wrap the input[type=file]
in a label tag, then style the label
to your liking, and hide the input
.
<label class="btn btn-default fileLabel" data-toggle="tooltip" data-placement="top" title="Upload">
<input type="file">
<span><i class="fa fa-upload"></i></span>
</label>
<style>
.fileLabel input[type="file"] {
position: fixed;
top: -1000px;
}
</style>
Purely CSS Solution.
Try the following commands in terminal, this will work better:
apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
You might get Component unavailable
if you import the jQuery script directly.
Maybe it's what @Conley was talking about...
You can use
@require http://userscripts.org/scripts/source/85365.user.js
which is an modified version to work on Greasemonkey, and then get the jQuery object
var $ = unsafeWindow.jQuery;
$("div").css("display", "none");
I was trying to also sort by a DateTime field descending and this seems to do the trick:
var ud = (from d in env
orderby -d.ReportDate.Ticks
select d.ReportDate.ToString("yyyy-MMM") ).Distinct();
Another more versatile way is to use find
:
sed -i 's/asd/dsg/g' $(find . -type f -name 'xa*')
Do yourself.
def median(numbers):
"""
Calculate median of a list numbers.
:param numbers: the numbers to be calculated.
:return: median value of numbers.
>>> median([1, 3, 3, 6, 7, 8, 9])
6
>>> median([1, 2, 3, 4, 5, 6, 8, 9])
4.5
>>> import statistics
>>> import random
>>> numbers = random.sample(range(-50, 50), k=100)
>>> statistics.median(numbers) == median(numbers)
True
"""
numbers = sorted(numbers)
mid_index = len(numbers) // 2
return (
(numbers[mid_index] + numbers[mid_index - 1]) / 2 if mid_index % 2 == 0
else numbers[mid_index]
)
if __name__ == "__main__":
from doctest import testmod
testmod()
Here I like to use https://www.netresize.net/index.php?c=3a&id=11#buyopt. But it is paid version.
You also can get their source codes if you buy 1 Site License (Unlimited Developers).
How ever I am finding the nuget package solution.
The warning message is because your "Type" variable was made a factor and "lunch" was not a defined level. Use the stringsAsFactors = FALSE
flag when making your data frame to force "Type" to be a character.
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> str(fixed)
'data.frame': 3 obs. of 2 variables:
$ Type : Factor w/ 1 level "": NA 1 1
$ Amount: chr "100" "0" "0"
>
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3),stringsAsFactors=FALSE)
> fixed[1, ] <- c("lunch", 100)
> str(fixed)
'data.frame': 3 obs. of 2 variables:
$ Type : chr "lunch" "" ""
$ Amount: chr "100" "0" "0"
From the Spring reference, 3.2.3.1 Naming Beans:
Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.
When using XML-based configuration metadata, you use the 'id' or 'name' attributes to specify the bean identifier(s). The 'id' attribute allows you to specify exactly one id, and as it is a real XML element ID attribute, the XML parser is able to do some extra validation when other elements reference the id; as such, it is the preferred way to specify a bean id. However, the XML specification does limit the characters which are legal in XML IDs. This is usually not a constraint, but if you have a need to use one of these special XML characters, or want to introduce other aliases to the bean, you may also or instead specify one or more bean ids, separated by a comma (,), semicolon (;), or whitespace in the 'name' attribute.
So basically the id
attribute conforms to the XML id attribute standards whereas name
is a little more flexible. Generally speaking, I use name
pretty much exclusively. It just seems more "Spring-y".
This will dismiss some elements - you should extend it like this in order to support a wider array of controls. For a brief discussion, have a look here
/// <summary>
/// Helper methods for UI-related tasks.
/// </summary>
public static class UIHelper
{
/// <summary>
/// Finds a parent of a given item on the visual tree.
/// </summary>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="child">A direct or indirect child of the
/// queried item.</param>
/// <returns>The first parent item that matches the submitted
/// type parameter. If not matching item can be found, a null
/// reference is being returned.</returns>
public static T TryFindParent<T>(DependencyObject child)
where T : DependencyObject
{
//get parent item
DependencyObject parentObject = GetParentObject(child);
//we've reached the end of the tree
if (parentObject == null) return null;
//check if the parent matches the type we're looking for
T parent = parentObject as T;
if (parent != null)
{
return parent;
}
else
{
//use recursion to proceed with next level
return TryFindParent<T>(parentObject);
}
}
/// <summary>
/// This method is an alternative to WPF's
/// <see cref="VisualTreeHelper.GetParent"/> method, which also
/// supports content elements. Do note, that for content element,
/// this method falls back to the logical tree of the element!
/// </summary>
/// <param name="child">The item to be processed.</param>
/// <returns>The submitted item's parent, if available. Otherwise
/// null.</returns>
public static DependencyObject GetParentObject(DependencyObject child)
{
if (child == null) return null;
ContentElement contentElement = child as ContentElement;
if (contentElement != null)
{
DependencyObject parent = ContentOperations.GetParent(contentElement);
if (parent != null) return parent;
FrameworkContentElement fce = contentElement as FrameworkContentElement;
return fce != null ? fce.Parent : null;
}
//if it's not a ContentElement, rely on VisualTreeHelper
return VisualTreeHelper.GetParent(child);
}
}
Put the part from BEGIN....END{}
inside a file and name it like my.awk.
And then execute it like below:
awk -f my.awk life.csv >output.txt
Also I see a field separator as ,
. You can add that in the begin block of the .awk file as FS=","
The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.
This is the answer that worked for me:
foreach (var x in jobj)
{
var key = ((JProperty) (x)).Name;
var jvalue = ((JProperty)(x)).Value ;
}
For python 3, the default encoding would be "utf-8". Following steps are suggested in the base documentation:https://docs.python.org/2/library/csv.html#csv-examples in case of any problem
Create a function
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
Then use the function inside the reader, for e.g.
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data))
According to Microsoft, the allocation unit size "Specifies the cluster size for the file system" - so it is the value shown for "Bytes Per Cluster" as shown in:
fsutil fsinfo ntfsinfo C:
Just found this online at http://snipplr.com/view/62238/get-youtube-video-id-very-robust/
function getYouTubeId($url) {
// Format all domains to http://domain for easier URL parsing
str_replace('https://', 'http://', $url);
if (!stristr($url, 'http://') && (strlen($url) != 11)) {
$url = 'http://' . $url;
}
$url = str_replace('http://www.', 'http://', $url);
if (strlen($url) == 11) {
$code = $url;
} else if (preg_match('/http:\/\/youtu.be/', $url)) {
$url = parse_url($url, PHP_URL_PATH);
$code = substr($url, 1, 11);
} else if (preg_match('/watch/', $url)) {
$arr = parse_url($url);
parse_str($url);
$code = isset($v) ? substr($v, 0, 11) : false;
} else if (preg_match('/http:\/\/youtube.com\/v/', $url)) {
$url = parse_url($url, PHP_URL_PATH);
$code = substr($url, 3, 11);
} else if (preg_match('/http:\/\/youtube.com\/embed/', $url, $matches)) {
$url = parse_url($url, PHP_URL_PATH);
$code = substr($url, 7, 11);
} else if (preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+#", $url, $matches) ) {
$code = substr($matches[0], 0, 11);
} else {
$code = false;
}
if ($code && (strlen($code) < 11)) {
$code = false;
}
return $code;
}
intern ? symbol Returns the Symbol corresponding to str, creating the symbol if it did not previously exist
"edition".intern # :edition
First run your IDE or CMD as Administrator and run the following:
pip install pipwin
pipwin install pyaudio
I had a different root cause
I had a script that basically searches all branches matching jira issue key in the for "PRJ-1234" among all branches to execute a git branch checkout command on the matching branch
The problem in my case was 2 or more branches shared the same jira key and hence caused my script to fail with the aforementioned error
By deleting the old unused branch and making sure only a single branch had the jira key reference fixed the problem
Here's my code in case someone wants to use it
git remote update
git fetch --all --prune
git branch -r --list *$1* | xargs git checkout --force
save this as switchbranch.sh
Then use it from the terminal ./switchbranch.sh PRJ-1234
How could you do that? You need a variable or field of type T where you can store the object after the cast, but how can you have such a variable or field if you know T only at runtime? So, no, it's not possible.
Type type = GetSomeType();
Object @object = GetSomeObject();
??? xyz = @object.CastTo(type); // How would you declare the variable?
xyz.??? // What methods, properties, or fields are valid here?
I Solved it. I just had to add the path of android studio's platform-tools after removing my earlier eclipse's path. I don't know, maybe some conflict in the command.
All you need is a ADODB.Connection
Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset ' Microsoft ActiveX Data Objects Library
Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"
Set rs = cnn.Execute(SQLQuery) ' Retrieve the data
The problem still not resolved after remove the '.', then it start points the error to my folder. As i added this folder first time then i restarted the PyCharm and it automatically resolved the issue
The org.apache.commons.text.StringSubstitutor helper class from Apache Commons Text provides named variable substitution
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String resolved = new StringSubstitutor(valuesMap).replace("The ${animal} jumped over the ${target}.");
System.out.println(resolved); // The quick brown fox jumped over the lazy dog.
In my experience, the best way is a combination of these.
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
Will give you the bin folderDirectory.GetCurrentDirectory()
Works fine on .Net Core but not .Net and will give you the root directory of the projectSystem.AppContext.BaseDirectory
and AppDomain.CurrentDomain.BaseDirectory
Works fine in .Net but not .Net core and will give you the root directory of the projectIn a class library that is supposed to target.Net and .Net core I check which framework is hosting the library and pick one or the other.
db.collection.find().hint( { $natural : -1 } ).sort(field: 1/-1).limit(n)
according to mongoDB Documentation:
You can specify { $natural : 1 } to force the query to perform a forwards collection scan.
You can also specify { $natural : -1 } to force the query to perform a reverse collection scan.
You can do almost the same yourself. Open Environment Variables and click "New" Button in the "User Variables for ..." .
Variable Name: ~
Variable Value: Click "Browse Directory..." button and choose a directory which you want.
And after this, open cmd and type this:
cd %~%
. It works.
You are reading all rows into a list, then processing that list. Don't do that.
Process your rows as you produce them. If you need to filter the data first, use a generator function:
import csv
def getstuff(filename, criterion):
with open(filename, "rb") as csvfile:
datareader = csv.reader(csvfile)
yield next(datareader) # yield the header row
count = 0
for row in datareader:
if row[3] == criterion:
yield row
count += 1
elif count:
# done when having read a consecutive series of rows
return
I also simplified your filter test; the logic is the same but more concise.
Because you are only matching a single sequence of rows matching the criterion, you could also use:
import csv
from itertools import dropwhile, takewhile
def getstuff(filename, criterion):
with open(filename, "rb") as csvfile:
datareader = csv.reader(csvfile)
yield next(datareader) # yield the header row
# first row, plus any subsequent rows that match, then stop
# reading altogether
# Python 2: use `for row in takewhile(...): yield row` instead
# instead of `yield from takewhile(...)`.
yield from takewhile(
lambda r: r[3] == criterion,
dropwhile(lambda r: r[3] != criterion, datareader))
return
You can now loop over getstuff()
directly. Do the same in getdata()
:
def getdata(filename, criteria):
for criterion in criteria:
for row in getstuff(filename, criterion):
yield row
Now loop directly over getdata()
in your code:
for row in getdata(somefilename, sequence_of_criteria):
# process row
You now only hold one row in memory, instead of your thousands of lines per criterion.
yield
makes a function a generator function, which means it won't do any work until you start looping over it.
@SuppressWarnings("unchecked")
Map<String,String[]> requestMapper=request.getParameterMap();
JsonObject jsonObject=new JsonObject();
for(String key:requestMapper.keySet()){
jsonObject.addProperty(key, requestMapper.get(key)[0]);
}
All params will be stored in jsonObject
.
In TSQL, the modulo is done with a percent sign.
SELECT 38 % 5 would give you the modulo 3
All the above failed for me. But I noticed shift + ? Tab worked as expected (outdenting the line).
So I looked for the "Indent Line" shortcut (which was assigned to alt + ctrl + cmd + 0 ), assigned it to tab, and now I'm happy again.
I also use tab to accept snippet suggestions, so I've set the "when" of "Indent Line" to editorTextFocus && !editorReadonly && !inSnippetMode && !suggestWidgetVisible
.
Here you go. Just specify the chars you want to allow on the first line.
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use
java.security.SecureRandom
instead. Values produced byjava.util.Random
andjava.util.concurrent.ThreadLocalRandom
are mathematically predictable.
You can manage it with a double cast :
@SuppressWarnings("unchecked")
Class<List<Foo>> cls = (Class<List<Foo>>)(Object)List.class
Modify the DataNode class so that it implements Comparable interface.
public int compareTo(DataNode o)
{
return(degree - o.degree);
}
then just use
Collections.sort(nodeList);
If you move your for loop, you won't have to make multiple connections. Just a quick edit to your code block (by no means completely correct):
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= @"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
As to executing multiple SQL commands at once, please look at this link: Multiple statements in single SqlCommand
Escape the hyphen.
[a-zA-Z0-9!$* \t\r\n\-]
UPDATE:
Never mind this answer - you can add the hyphen to the group but you don't have to escape it. See Konrad Rudolph's answer instead which does a much better job of answering and explains why.
You have set a fixed width and height in your svg tag. This is probably the root of your problem. Try not removing those and set the width and height (if needed) using CSS instead.
Check that there are no missing references - to do this, go to the database window and click on "Modules", then "Design", then select the menu "Tools" and then "References". Or try doing a compile and see if it compiles fully (go to the Debug menu then select Compile) - it might tell you of a missing reference e.g. Microsoft Office 11.0 Object Library. Select References from the Tools menu again and see if any references are ticked and say "MISSING:". In some cases you can select a different version from the list, if 11.0 is missing, look for version 12.0 then recompile. That usually does the trick for me.
if you got troubles with windows cmd command and .bat just escape percents like that
git show -s --format=%%ct
The % character has a special meaning for command line parameters and FOR parameters. To treat a percent as a regular character, double it: %%
You don't even need to do the check manually, File.Open does it for you. Try:
using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append)))
{
Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx
You can also load the context while defining the servlet itself (WebApplicationContext)
<servlet>
<servlet-name>admin</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/*.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>admin</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
rather than (ApplicationContext)
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
or can do both together.
Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet
) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet
etc)
Context loaded by ContextLoaderListener
will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.
It sounds like you're using Subclipse; is that correct? If so, there's a great list of decorators and their descriptions at this answer by Tim Stone.
Here's the relevant snippet for your case:
- A file not under version control. These are typically new files that you have not committed to the repository yet.
- A file with no local changes.
I had to unslick the carousel before the ajax call starts, but you can't do that until there is already a slick carousel. So, I set a variable to 0 and only run unslick after it changed
var slide = 0
if(slide>0)
$('#ui-id-1').slick('unslick');
$.ajax({
//do stuff, here
},
success: function( data ) {
$('#ui-id-1').slick();
slide++;
}
One of the most significant JIT optimizations is method inlining. Java can even inline virtual methods if it can guarantee runtime correctness. This kind of optimization usually cannot be performed by standard static compilers because it needs whole-program analysis, which is hard because of separate compilation (in contrast, JIT has all the program available to it). Method inlining improves other optimizations, giving larger code blocks to optimize.
Standard memory allocation in Java/C# is also faster, and deallocation (GC) is not much slower, but only less deterministic.
Here's a method which is similar to Kelly's but will remove any pre-existing script with the same source, and uses jQuery.
<script>
function reload_js(src) {
$('script[src="' + src + '"]').remove();
$('<script>').attr('src', src).appendTo('head');
}
reload_js('source_file.js');
</script>
Note that the 'type' attribute is no longer needed for scripts as of HTML5. (http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#the-script-element)
A command-line version of Bell's answer:
createdb -O ownername -T originaldb newdb
This should be run under the privileges of the database master, usually postgres.
Your error is in UpdaterServiceManager in onCreate and showNotification method.
You are trying to show notification
from Service using Activity Context
. Whereas Every Service has its own Context,
just use the that. You don't need to pass a Service an Activity's Context.
I don't see why you need a specific Activity's Context to show Notification.
Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.
You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference
CSS was designed to affect presentation, not behaviour.
You could use some JavaScript.
document.links[0].onclick = function(event) {
event.preventDefault();
};
The SyntheticEvent interface is generic:
interface SyntheticEvent<T> {
...
currentTarget: EventTarget & T;
...
}
(Technically the currentTarget
property is on the parent BaseSyntheticEvent type.)
And the currentTarget
is an intersection of the generic constraint and EventTarget
.
Also, since your events are caused by an input element you should use the ChangeEvent
(in definition file, the react docs).
Should be:
update = (e: React.ChangeEvent<HTMLInputElement>): void => {
this.props.login[e.currentTarget.name] = e.currentTarget.value
}
(Note: This answer originally suggested using React.FormEvent
. The discussion in the comments is related to this suggestion, but React.ChangeEvent
should be used as shown above.)
You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window
and document
both fit the bill (with just a few differences).
From mozilla dev network:
addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.
So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.
In Angular 2+, try the @Input decorator
It allows for some nice property binding between parent and child components.
First create a global variable in the parent to hold the object/property that will be passed to the child.
Next create a global variable in the child to hold the object/property passed from the parent.
Then in the parent html, where the child template is used, add square brackets notation with the name of the child variable, then set it equal to the name of the parent variable. Example:
<child-component-template [childVariable] = parentVariable>
</child-component-template>
Finally, where the child property is defined in the child component, add the Input decorator:
@Input()
public childVariable: any
When your parent variable is updated, it should pass the updates to the child component, which will update its html.
Also, to trigger a function in the child component, take a look at ngOnChanges.
Interestingly the way Postman does POST is a complete GET operation with these 2 additional options:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
Just another way, and it works very well.
As others mentioned in Bootstrap 3, you can use nest/embed techniques.
However it is becoming more obvious to use pretty awesome feature from Bootstrap 4 now. you simple have the option to use the col-{breakpoint}-auto
classes (e.g. col-md-auto
) to make columns size itself automatically based on the natural width of its content. check this for example
For those who like boost:
boost::filesystem::path mySourcePath("foo.bar");
boost::filesystem::path myTargetPath("bar.foo");
// Variant 1: Overwrite existing
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::overwrite_if_exists);
// Variant 2: Fail if exists
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::fail_if_exists);
Note that boost::filesystem::path is also available as wpath for Unicode. And that you could also use
using namespace boost::filesystem
if you do not like those long type names
Use Callback. It worked for me!
export function addProduct(props, callback) {
return dispatch =>
axios.post(`${ROOT_URL}/cart`, props, config)
.then(response => {
dispatch({ type: types.AUTH_USER });
localStorage.setItem('token', response.data.token);
callback();
});
}
In component, you just have to add the callback
this.props.addProduct(props, () => this.props.history.push('/cart'))
You need the following code below. At a glance, this may look like any old code that I made up. However, what I did was look at the source code for http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.31/com/mysql/jdbc/PreparedStatement.java. Then after that, I carefully looked through the code of setString(int parameterIndex, String x) to find the characters which it escapes and customised this to my own class so that it can be used for the purposes that you need. After all, if this is the list of characters that Oracle escapes, then knowing this is really comforting security-wise. Maybe Oracle need a nudge to add a method similar to this one for the next major Java release.
public class SQLInjectionEscaper {
public static String escapeString(String x, boolean escapeDoubleQuotes) {
StringBuilder sBuilder = new StringBuilder(x.length() * 11/10);
int stringLength = x.length();
for (int i = 0; i < stringLength; ++i) {
char c = x.charAt(i);
switch (c) {
case 0: /* Must be escaped for 'mysql' */
sBuilder.append('\\');
sBuilder.append('0');
break;
case '\n': /* Must be escaped for logs */
sBuilder.append('\\');
sBuilder.append('n');
break;
case '\r':
sBuilder.append('\\');
sBuilder.append('r');
break;
case '\\':
sBuilder.append('\\');
sBuilder.append('\\');
break;
case '\'':
sBuilder.append('\\');
sBuilder.append('\'');
break;
case '"': /* Better safe than sorry */
if (escapeDoubleQuotes) {
sBuilder.append('\\');
}
sBuilder.append('"');
break;
case '\032': /* This gives problems on Win32 */
sBuilder.append('\\');
sBuilder.append('Z');
break;
case '\u00a5':
case '\u20a9':
// escape characters interpreted as backslash by mysql
// fall through
default:
sBuilder.append(c);
}
}
return sBuilder.toString();
}
}
You can add and retrieve a numpy array from dataframe using this:
import numpy as np
import pandas as pd
df = pd.DataFrame({'b':range(10)}) # target dataframe
a = np.random.normal(size=(10,2)) # numpy array
df['a']=a.tolist() # save array
np.array(df['a'].tolist()) # retrieve array
This builds on the previous answer that confused me because of the sparse part and this works well for a non-sparse numpy arrray.
Look here.
Basically you have to do bind params:
$sql = "SELECT username FROM users WHERE locationid IN (SELECT locationid FROM locations WHERE countryid=?)";
$this->db->query($sql, '__COUNTRY_NAME__');
But, like Mr.E said, use joins:
$sql = "select username from users inner join locations on users.locationid = locations.locationid where countryid = ?";
$this->db->query($sql, '__COUNTRY_NAME__');
If you want to use it on XML content then add the below line in your Gradle file:
applicationVariants.all { variant ->
variant.resValue "string", "versionName", variant.versionName
}
And then use it on your XML content like this:
<TextView
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/versionName" />
FYI Bootstrap 3 handles the left property automatically. So simply adding this CSS will change the width and keep it centered:
.modal .modal-dialog { width: 800px; }
The ol, ul lists will work if you want you can also use a table with border: none in the css.
I don't know much about the MySQL command line interface, but assuming you only need help with the bashing, you should try to either swap the commands around like so:
myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p$password)
which echos the string into MySQL. Or, you can be more fancy and use some new bash-features (the here string)
myvariable=$(mysql database -u $user -p$password<<<"SELECT A, B, C FROM table_a")
resulting in the same thing (assuming you're using a recent enough bash version), without involving echo.
Please note that the -p$password is not a typo, but is the way MySQL expects passwords to be entered through the command line (with no space between the option and value).
Note that myvariable will contain everything that MySQL outputs on standard out (usually everything but error messages), including any and all column headers, ASCII-art frames and so on, which may or may not be what you want.
EDIT:
As has been noted, there appears to be a -e
parameter to MySQL, I'd go for that one, definitely.
Note: only use this approach for images that are private and will always be!
The ssh key remains stored within the image, even if you remove the key in a layer command after adding it (see comments in this post).
In my case this is ok, so this is what I am using:
# Setup for ssh onto github
RUN mkdir -p /root/.ssh
ADD id_rsa /root/.ssh/id_rsa
RUN chmod 700 /root/.ssh/id_rsa
RUN echo "Host github.com\n\tStrictHostKeyChecking no\n" >> /root/.ssh/config
You can also do it like this
public Map<Boolean, List<Student>> getpartitionMap(List<Student> studentsList) {
List<Predicate<Student>> allPredicates = getAllPredicates();
Predicate<Student> compositePredicate = allPredicates.stream()
.reduce(w -> true, Predicate::and)
Map<Boolean, List<Student>> studentsMap= studentsList
.stream()
.collect(Collectors.partitioningBy(compositePredicate));
return studentsMap;
}
public List<Student> getValidStudentsList(Map<Boolean, List<Student>> studentsMap) throws Exception {
List<Student> validStudentsList = studentsMap.entrySet()
.stream()
.filter(p -> p.getKey() == Boolean.TRUE)
.flatMap(p -> p.getValue().stream())
.collect(Collectors.toList());
return validStudentsList;
}
public List<Student> getInValidStudentsList(Map<Boolean, List<Student>> studentsMap) throws Exception {
List<Student> invalidStudentsList =
partionedByPredicate.entrySet()
.stream()
.filter(p -> p.getKey() == Boolean.FALSE)
.flatMap(p -> p.getValue().stream())
.collect(Collectors.toList());
return invalidStudentsList;
}
With flatMap
you will get just List<Student>
instead of List<List<Student>>
.
Thanks
It should not be considered as a question of best for usage, but it really depends on the use case or the scenario.
Synchronized Methods
An entire method can be marked as synchronized resulting an implicit lock on the this reference (instance methods) or class (static methods). This is very convenient mechanism to achieve synchronization.
Steps A thread access the synchronized method. It implicitly acquires the lock and execute the code. If other thread want to access the above method, it has to wait. The thread can't get the lock, will be blocked and has to wait till the lock is released.
Synchronized Blocks
To acquire a lock on an object for a specific set of code block, synchronized blocks are the best fit. As a block is sufficient, using a synchronized method will be a waste.
More specifically with Synchronized Block , it is possible to define the object reference on which are want to acquire a lock.
I think you can change your query and try it like :
$res=User::where('id',$id)->delete();
In my case, I was using a pair of keys that didn't have the default names id_rsa
and id_rsa.pub
.
Producing keys with these names solved the problem, and I actually found it looking at the output of ssh -vT my_gitlab_address
. Strange fact: it worked on one computer with Ubuntu, but not on others with different distributions and older versions of OpenSSH.
Another thing that can give you hell with JQuery Dialog positioning, especially for documents larger than the browser view port - you must add the declaration
<!DOCTYPE html>
At the top of your document.
Without it, jquery tends to put the dialog on the bottom of the page and errors may occur when trying to drag it.
If you are using Underscore JS, just use :
var result = _.chunk(arr,elements_per_chunk)
Most projects already use underscore as a dependency, anyways.
If you are a control freak like me, you may want to explicitly set all your font sizes:
import matplotlib.pyplot as plt
SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
Note that you can also set the sizes calling the rc
method on matplotlib
:
import matplotlib
SMALL_SIZE = 8
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)
# and so on ...
We can hide close button on form by setting this.ControlBox=false;
Note that this hides all of those sizing buttons. Not just the X. In some cases that may be fine.
Sort the file randomly and pick first 100
lines:
$ sort -R input | head -n 100 >output
Quoting Jacob Hallen:
The proper use of
__slots__
is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. [This use of__slots__
eliminates the overhead of one dict for every object.] While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.Unfortunately there is a side effect to slots. They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies. This is bad, because the control freaks should be abusing the metaclasses and the static typing weenies should be abusing decorators, since in Python, there should be only one obvious way of doing something.
Making CPython smart enough to handle saving space without
__slots__
is a major undertaking, which is probably why it is not on the list of changes for P3k (yet).
If you are just targeting specific domains you can try and add this in your application's Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
If you are using an earlier version of QT (<5) try this
QMAKE_CXXFLAGS += -std=c++0x
alert("Selected value is: "+$(".leaderMultiSelctdropdown").select2("val"));
alternatively, if you used a regular selectbox as base, you should be able to use the normal jquery call, too:
alert("Selected value is: "+$(".leaderMultiSelctdropdown").val());
both return an array of the selected keys.
onStart()
called when the activity is becoming visible to the user.
onResume()
called when the activity will start interacting with the user.
You may want to do different things in this cases.
See this link for reference.
If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:
netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672
for the remote access.
So, I spent about a day trying to figure out what was the issue; tried all the proposed solutions, but none of that worked like installing xcb libs or exporting Qt plugins folder. The solution that suggested to use QT_DEBUG_PLUGINS=1
to debug the issue didn't provide me a direct insight like in the answer - instead I was getting something about unresolved symbols within Qt5Core.
That gave me a hint, though: what if it's trying to use different files from different Qt installations? On my machine I had standard version installed in /home/username/Qt/
and some local builds within my project that I compiled by myself (I have other custom built kits as well in other locations). Whenever I tried to use any of the kits (installed by Qt maintenance tool or built by myself), I would get an "xcb error".
The solution was simple: provide the Qt path through CMAKE_PREFIX_PATH
and not though Qt5_DIR
as I did, and it solved the problem. Example:
cmake .. -DCMAKE_PREFIX_PATH=/home/username/Qt/5.11.1/gcc_64
After trying almost everything on this thread and others, continuing to Google, the only thing that worked for me, in the end, was to start Visual Studio as my AD user via command line:
cd C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE
runas /netonly /user:<comp\name.surname> devenv.exe
Original issue: [1]: https://developercommunity.visualstudio.com/content/problem/304224/git-failed-with-a-fatal-errorauthentication-failed.html
My situation is I'm on a personal machine connecting to a company's internal/local devops server (not cloud-based) that uses AD authorization. I had no issue with TFS, but with git could not get the clone to work (Git failed with a fatal error. Authentication failed for [url]) until I did that.
In case if you are getting an error as "unterminated string constant", use the following razor syntax :
<input type="button" onclick="@("location.href='"+ Url.Action("Index","Test")+ "'")" />
If you want to do this often, you can create a keybindings file in your Library to map it to a key combination.
In ~/Library create a directory named KeyBindings. Create a file named DefaultKeyBinding.dict inside the directory. You can add key bindings in this format:
{
"x" = (insertText:, "\U23CF");
"y" = (insertText:, "hi"); /* warning: this will change 'y' to 'hi'! */
}
The LHS is the key combination you'll hit to enter the character. You can use the following characters to indicate command keys:
@ - Command
~ - Option
^ - Control
You'll need to look up the unicode for your character (in this case, ? is \U2234). So to type this character whenever you typed Control-M, you'd use
"^m" = (insertText:, "\U2234");
You can find more information here: http://www.hcs.harvard.edu/~jrus/site/cocoa-text.html
Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});
I was brought here for a reason not explicitly mentioned in the answers so far, so to save others the trouble:
The error also occurs if the function arguments have changed order - for the same reason as in the accepted answer: the positional arguments clash with the keyword arguments.
In my case it was because the argument order of the Pandas set_axis
function changed between 0.20 and 0.22:
0.20: DataFrame.set_axis(axis, labels)
0.22: DataFrame.set_axis(labels, axis=0, inplace=None)
Using the commonly found examples for set_axis results in this confusing error, since when you call:
df.set_axis(['a', 'b', 'c'], axis=1)
prior to 0.22, ['a', 'b', 'c']
is assigned to axis because it's the first argument, and then the positional argument provides "multiple values".
As of version 5.4, PHP supports traits. This is not exactly what you are looking for, but a simplistic trait based approach would be:
trait StudentTrait {
protected $id;
protected $name;
final public function setId($id) {
$this->id = $id;
return $this;
}
final public function getId() { return $this->id; }
final public function setName($name) {
$this->name = $name;
return $this;
}
final public function getName() { return $this->name; }
}
class Student1 {
use StudentTrait;
final public function __construct($id) { $this->setId($id); }
}
class Student2 {
use StudentTrait;
final public function __construct($id, $name) { $this->setId($id)->setName($name); }
}
We end up with two classes, one for each constructor, which is a bit counter-productive. To maintain some sanity, I'll throw in a factory:
class StudentFactory {
static public function getStudent($id, $name = null) {
return
is_null($name)
? new Student1($id)
: new Student2($id, $name)
}
}
So, it all comes down to this:
$student1 = StudentFactory::getStudent(1);
$student2 = StudentFactory::getStudent(1, "yannis");
It's a horribly verbose approach, but it can be extremely convenient.
Try this snippet
list.onclick = function(e) {_x000D_
e.preventDefault();_x000D_
_x000D_
var elm = e.target;_x000D_
var audio = document.getElementById('audio');_x000D_
_x000D_
var source = document.getElementById('audioSource');_x000D_
source.src = elm.getAttribute('data-value');_x000D_
_x000D_
audio.load(); //call this to just preload the audio without playing_x000D_
audio.play(); //call this to play the song right away_x000D_
};
_x000D_
<ul style="list-style: none">_x000D_
<li>Audio Files_x000D_
<ul id="list">_x000D_
<li><a href="#" data-value="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga">Death_Becomes_Fur.oga</a></li>_x000D_
<li><a href="#" data-value="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4">Death_Becomes_Fur.mp4</a></li>_x000D_
<li><a href="#" data-value="http://media.w3.org/2010/11/rrs006.oga">rrs006.oga</a></li>_x000D_
<li><a href="#" data-value="http://media.w3.org/2010/05/sound/sound_90.mp3">sound_90.mp3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<audio id="audio" controls="controls">_x000D_
<source id="audioSource" src=""></source>_x000D_
Your browser does not support the audio format._x000D_
</audio>
_x000D_
JSFiddle http://jsfiddle.net/jm6ky/2/
you should add plug in to your local setting of firefox in your user home
vladimir@shinsengumi ~/.mozilla/plugins $ pwd
/home/vladimir/.mozilla/plugins
vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
lrwxrwxrwx 1 vladimir vladimir 60 Jan 1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so
In host computer/server go to Sql server management studio --> open Security Section on left hand --> right click on Login, select New Login and then create a new account for your database which you want to connect to.
Check the TCP/IP Protocol is Enable. go to All programs --> Microsoft SQL server 2008 --> Configuration Tools --> open Sql server configuration manager. On the left hand select client protocols (based on your operating system 32/64 bit). On the right hand, check TCP/IP Protocol be Enabled.
In Remote computer/server, open Data source administrator. Control panel --> Administrative tools --> Data sources (ODBC).
In User DSN or System DSN , click Add button and select Sql Server driver and then press Finish.
Enter Name.
Enter Server, note that: if you want to enter host computer address, you should enter that`s IP address without "\\". eg. 192.168.1.5 and press Next.
Select With SQL Server authentication using a login ID and password entered by the user.
At the bellow enter your login ID and password which you created on first step. and then click Next.
If shown Database is your database, click Next and then Finish.
small update for swift 5:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
self.present(refreshAlert, animated: true, completion: nil)
An alternative for the bind() method.
Use the click() method, do something like this:
commentbtn.click({id: 10, name: "João"}, onClickCommentBtn);
function onClickCommentBtn(event)
{
alert("Id=" + event.data.id + ", Name = " + event.data.name);
}
Or, if you prefer:
commentbtn.click({id: 10, name: "João"}, function (event) {
alert("Id=" + event.data.id + ", Nome = " + event.data.name);
});
It will show an alert box with the following infos:
Id = 10, Name = João
Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python
By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.
To disable this, use: struct.unpack("=BH", data)
. This will use standard alignment, which doesn't add padding:
>>> struct.calcsize('=BH')
3
The =
character will use native byte ordering. You can also use <
or >
instead of =
to force little-endian or big-endian byte ordering, respectively.
"Segmentation fault (core dumped)"
is the string that Linux prints when a program exits with a SIGSEGV
signal and you have core creation enabled. This means some program has crashed.
If you're actually getting this error from running Python, this means the Python interpreter has crashed. There are only a few reasons this can happen:
You're using a third-party extension module written in C, and that extension module has crashed.
You're (directly or indirectly) using the built-in module ctypes
, and calling external code that crashes.
There's something wrong with your Python installation.
You've discovered a bug in Python that you should report.
The first is by far the most common. If your q
is an instance of some object from some third-party extension module, you may want to look at the documentation.
Often, when C modules crash, it's because you're doing something which is invalid, or at least uncommon and untested. But whether it's your "fault" in that sense or not - that doesn't matter. The module should raise a Python exception that you can debug, instead of crashing. So, you should probably report a bug to whoever wrote the extension. But meanwhile, rather than waiting 6 months for the bug to be fixed and a new version to come out, you need to figure out what you did that triggered the crash, and whether there's some different way to do what you want. Or switch to a different library.
On the other hand, since you're reading and printing out data from somewhere else, it's possible that your Python interpreter just read the line "Segmentation fault (core dumped)"
and faithfully printed what it read. In that case, some other program upstream presumably crashed. (It's even possible that nobody crashed—if you fetched this page from the web and printed it out, you'd get that same line, right?) In your case, based on your comment, it's probably the Java program that crashed.
If you're not sure which case it is (and don't want to learn how to do process management, core-file inspection, or C-level debugging today), there's an easy way to test: After print line
add a line saying print "And I'm OK"
. If you see that after the Segmentation fault
line, then Python didn't crash, someone else did. If you don't see it, then it's probably Python that's crashed.
Try getting the “left part” of the url, like this:
string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
This will give you either http://localhost:5858
or https://www.somedomainname.com
whether you're on local or production. If you want to drop the www
part, you should configure IIS to do so, but that's another topic.
Do note that the resulting URL will not have a trailing slash.
You can also use js map function:
$("#multipleSelect :selected").map(function(i, el) {
return $(el).val();
}).get();
And then you can get any property of the option
element:
return $(el).text();
return $(el).data("mydata");
return $(el).prop("disabled");
etc...
http://www.w3schools.com/cssref/css3_pr_animation-keyframes.asp
it is actually a browser issue... use -webkit- for chrome
Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.
I got the same error too .. my error is unmet dependencies /var/cache/apt/archives/mongodb-org-server_4.4.2_amd64.deb
and I ran this:
sudo dpkg -i --force-all /var/cache/apt/archives/mongodb-org-server_4.4.2_amd64.deb
and it worked
You need to use padding on the list item layout so space is added on the edges of the item (just increasing the font size won't do that).
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/text1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp" />
According to this : we can write this help function :
public static int convertBinaryToDecimal(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
int value = Character.getNumericValue(str.charAt(i));
result = result * 2 + value;
}
return result;
}
You should check that fractional part of the number is 0. Use
x==Math.ceil(x)
or
x==Math.round(x)
or something like that
(1) SQLite has a built in rowid
pseudo-column so this works:
sqldf("select min(rowid) rowid, id, string
from test
group by id")
giving:
rowid id string
1 1 1 A
2 3 2 B
3 5 3 C
4 7 4 D
5 9 5 E
(2) Also sqldf
itself has a row.names=
argument:
sqldf("select min(cast(row_names as real)) row_names, id, string
from test
group by id", row.names = TRUE)
giving:
id string
1 1 A
3 2 B
5 3 C
7 4 D
9 5 E
(3) A third alternative which mixes the elements of the above two might be even better:
sqldf("select min(rowid) row_names, id, string
from test
group by id", row.names = TRUE)
giving:
id string
1 1 A
3 2 B
5 3 C
7 4 D
9 5 E
Note that all three of these rely on a SQLite extension to SQL where the use of min
or max
is guaranteed to result in the other columns being chosen from the same row. (In other SQL-based databases that may not be guaranteed.)
Yes, it's possible, from @Fábio Zangirolami answer
audio::-webkit-media-controls-panel, video::-webkit-media-controls-panel {
background-color: red;
}
The solution @miki725 is absolutely correct. Alternatively, if you would like to use the args
attribute as opposed to kwargs
, then you can simply modify your code as follows:
project_id = 4
reverse('edit_project', args=(project_id,))
An example of this can be found in the documentation. This essentially does the same thing, but the attributes are passed as arguments. Remember that any arguments that are passed need to be assigned a value before being reversed. Just use the correct namespace, which in this case is 'edit_project'
.
You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Be sure that the LocationListener you're implementing is from the google api, that is import this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
and it should work just fine.
It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html
Try this:
onclick="javascript:location.href='http://www.uol.com.br/'"
Worked fine for me in Firefox, Chrome and IE (wow!!)
I was just working on this, I may be a bit late, but I did a workaround. Here are steps: - Get current time from whatever timezone the app is fired.- - Get time zone offset of that zone from gmt 0. then add your timezone value in miliseconds. You will get the date in your time zone. I added some extra code to remove anything after the actual time.
getCurrentDate() {
var date = new Date();
var newDate = new Date(8 * 60 * 60000 + date.valueOf() +
(date.getTimezoneOffset() * 60000));
var ampm = newDate.getHours() < 12 ? ' AM' : ' PM';
var strDate = newDate + '';
return (strDate).substring(0, strDate.indexOf(' GMT')) + ampm
}
Use -C
option of tar:
tar zxvf <yourfile>.tar.gz -C /usr/src/
and then, the content of the tar should be in:
/usr/src/<yourfile>
In perl, for an input of 1 (A), 27 (AA), etc.
sub excel_colname {
my ($idx) = @_; # one-based column number
--$idx; # zero-based column index
my $name = "";
while ($idx >= 0) {
$name .= chr(ord("A") + ($idx % 26));
$idx = int($idx / 26) - 1;
}
return scalar reverse $name;
}
Basically you are positioning the cursor before the first row and then requesting data. You need to move the cursor to the first row.
result.next();
String foundType = result.getString(1);
It is common to do this in an if statement or loop.
if(result.next()){
foundType = result.getString(1);
}
If you don't mind using lodash try out https://github.com/rockabox/ng-lodash it wraps lodash completely so it is the only dependency and you don't need to load any other script files such as lodash.
Lodash is completely off of the window scope and no "hoping" that it's been loaded prior to your module.
I got the answer for the same ,
Go on SQL Server ? Tools ? Options ? Designers ? Table and Database Designers
and unselect Prevent saving changes that require table re-creation
2- Open table design view and that scroll your column up and down and save your changes.
One more map solution:
def square(a):
return map(pow, a, [2]*len(a))
You want to use Apache's CloseShieldInputStream
:
This is a wrapper that will prevent the stream from being closed. You'd do something like this.
InputStream is = null;
is = getStream(); //obtain the stream
CloseShieldInputStream csis = new CloseShieldInputStream(is);
// call the bad function that does things it shouldn't
badFunction(csis);
// happiness follows: do something with the original input stream
is.read();
Simplest code to shuffle:
import java.util.*;
public class ch {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
ArrayList<Integer> l=new ArrayList<Integer>(10);
for(int i=0;i<10;i++)
l.add(sc.nextInt());
Collections.shuffle(l);
for(int j=0;j<10;j++)
System.out.println(l.get(j));
}
}
as a single line:
long value_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch()).count();
Is there use case you can provide?
If you ever have the need for creating some dynamic sql it is appropriate to use sysname
as data type for variables holding table names, column names and server names.
From the documentation for FileSystemWatcher
:
The
OnCreated
event is raised as soon as a file is created. If a file is being copied or transferred into a watched directory, theOnCreated
event will be raised immediately, followed by one or moreOnChanged
events.
So, if the copy fails, (catch the exception), add it to a list of files that still need to be moved, and attempt the copy during the OnChanged
event. Eventually, it should work.
Something like (incomplete; catch specific exceptions, initialize variables, etc):
public static void listener_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine
(
"File Created:\n"
+ "ChangeType: " + e.ChangeType
+ "\nName: " + e.Name
+ "\nFullPath: " + e.FullPath
);
try {
File.Copy(e.FullPath, @"D:\levani\FolderListenerTest\CopiedFilesFolder\" + e.Name);
}
catch {
_waitingForClose.Add(e.FullPath);
}
Console.Read();
}
public static void listener_Changed(object sender, FileSystemEventArgs e)
{
if (_waitingForClose.Contains(e.FullPath))
{
try {
File.Copy(...);
_waitingForClose.Remove(e.FullPath);
}
catch {}
}
}
When you want to loop into a multiple dimensions array, you can use foreach like this:
foreach($data as $users){
foreach($users as $user){
echo $user['id'].' '.$user['c_name'].' '.$user['seat_no'].'<br/>';
}
}
I wrote a small post with examples on batch renaming using sed
couple of years ago:
http://www.guyrutenberg.com/2009/01/12/batch-renaming-using-sed/
For example:
for i in *; do
mv "$i" "`echo $i | sed "s/regex/replace_text/"`";
done
If the regex contains groups (e.g. \(subregex\
) then you can use them in the replacement text as \1\
,\2
etc.
The answer is to place the root dir to the location directives:
root /srv/www/ducklington.org/public_html;
Try this, with strings:
set "var=string1string2string3"
and with string variables:
set "var=%string1%%string2%%string3%"
Each iteration of the forEach()
will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to return
from the function at the appropriate point:
elementsCollection.forEach(function(element){
if (!element.shouldBeProcessed)
return; // stop processing this iteration
// This part will be avoided if not neccessary
doSomeLengthyOperation();
});
Following is a free list of tools you can use to check, test and verify your JS code:
Hope this helps.
Just look in file /var/log/auth.log on the server. Setting additional verbosity with -vv on the client side won't help, because the server is unlikely to offer too much information to a possible attacker.
You can't do this using sharer.php, but you can do something similar using the Dialog API. http://developers.facebook.com/docs/reference/dialogs/
http://www.facebook.com/dialog/feed?
app_id=123050457758183&
link=http://developers.facebook.com/docs/reference/dialogs/&
picture=http://fbrell.com/f8.jpg&
name=Facebook%20Dialogs&
caption=Reference%20Documentation&
description=Dialogs%20provide%20a%20simple,%20consistent%20interface%20for%20applications%20to%20interact%20with%20users.&
message=Facebook%20Dialogs%20are%20so%20easy!&
redirect_uri=http://www.example.com/response
The catch is you must create a dummy Facebook application just to have an app_id
. Note that your Facebook application doesn't have to do ANYTHING at all. Just be sure that it is properly configured, and you should be all set.
This is called an initialization list. It is for passing arguments to the constructor of a parent class. Here is a good link explaining it: Initialization Lists in C++
So I had this same problem with WSUS and it turned out that IIS 8.5 was not binding to my ipv4 ip address, but was binding to ipv6 address. when I accessed it via localhost:8580 it would translate it to the ipv6 localhost address, and thus would work. Accessing it via ip was a no go. I had to manually bind the address using netsh, then it worked right away. bloody annoying.
Steps:
netsh http add iplisten ipaddress (IPADDRESSOFYOURSERVER)
that's it. You should get:
IP address successfully added
I found the commands here https://serverfault.com/questions/123796/get-iis-7-5-to-listen-on-ipv6
In VBA we can not use if jj = 5 or 6 then
we must use if jj = 5 or jj = 6 then
maybe this:
If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then
you can use webview to show the pdf inside an application , for that you have to :
Many pdf to html online converter available.
Example:
consent_web = (WebView) findViewById(R.id.consentweb);
consent_web.getSettings().setLoadWithOverviewMode(true);
consent_web.getSettings().setUseWideViewPort(true);
consent_web.loadUrl("file:///android_asset/spacs_html.html");
A more concise solution. Try this directive.
Can also be used if you're using ReactiveForms.
export class NumberOnlyDirective {
private el: NgControl;
constructor(private ngControl: NgControl) {
this.el = ngControl;
}
// Listen for the input event to also handle copy and paste.
@HostListener('input', ['$event.target.value'])
onInput(value: string) {
// Use NgControl patchValue to prevent the issue on validation
this.el.control.patchValue(value.replace(/[^0-9]/g, ''));
}
}
The use it on your inputs like this:
<input matInput formControlName="aNumberField" numberOnly>
It may be a little late, but you could use the helper function time() to get the current timestamp. I tried this function and it did the job, no need for classes :).
You can find this in the official documentation at https://laravel.com/docs/5.0/templates
Regards.
If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:
def addNameToDictionary(d, tup):
if tup[0] not in d:
d[tup[0]] = {}
d[tup[0]][tup[1]] = [tup[2]]
Try like this: server.bind(("0.0.0.0", 6677))
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
Here's a solution that gives you a list of all executables and aliases. It's also portable to systems without xargs -d
(e.g. Mac OS X), and properly handles paths with spaces in them.
#!/bin/bash
(echo -n $PATH | tr : '\0' | xargs -0 -n 1 ls; alias | sed 's/alias \([^=]*\)=.*/\1/') | sort -u | grep "$@"
Usage: myscript.sh [grep-options] pattern
, e.g. to find all commands that begin with ls
, case-insensitive, do:
myscript -i ^ls
nvarchar(max)
field move that field to the bottom of your table.There's a simple way to this in any C-like language. The style is not Pythonic but works with pure Python:
def remove_html_markup(s):
tag = False
quote = False
out = ""
for c in s:
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
tag = False
elif (c == '"' or c == "'") and tag:
quote = not quote
elif not tag:
out = out + c
return out
The idea based in a simple finite-state machine and is detailed explained here: http://youtu.be/2tu9LTDujbw
You can see it working here: http://youtu.be/HPkNPcYed9M?t=35s
PS - If you're interested in the class(about smart debugging with python) I give you a link: https://www.udacity.com/course/software-debugging--cs259. It's free!
Right click on your solution and above properties is the option open Command Line which gives access to default cmd, powershell and developer command prompt alternatively you can use the shortcuts Alt+Space for Default (cmd), Shift+Alt+, for Dev (cmd), Shift+Alt+. for powershell
var icon1 = "imageA.png";
var icon2 = "imageB.png";
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: icon1,
title: "some marker"
});
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
marker.setIcon(icon1);
});
Try this :
Proc sql;
select employee, salary
from (select * from test having salary < max(salary))
having salary = max(salary)
;
Quit;
I was able to change the button's text like this:
import android.widget.RemoteViews;
//grab the layout, then set the text of the Button called R.id.Counter:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");
The real solution that I found for this issue was by disabling any XML Format post processors. I have added a post processor called "jp@gc - XML Format Post Processor
" and started noticing the error "Fatal Error :1:1: Content is not allowed in prolog
"
By disabling the post processor had stopped throwing those errors.
You can simply use shape method
df[df['LastName'] == 'Smith'].shape
Output
(1,1)
Which indicates 1 row and 1 column. This way you can get the idea of whole datasets
Let me explain the above code
DataframeName[DataframeName['Column_name'] == 'Value to match in column']
Why complicating too much? Solution is very simple
css:
.active-div{
position:relative;
}
.menu-div{
position:absolute;
top:0;
right:0;
display:none;
}
jquery:
$(function(){
$(".active-div").hover(function(){
$(".menu-div").prependTo(".active-div").show();
},function(){$(".menu-div").hide();
})
It works even if,
The issue is that your kubeconfig
is not right.
To auto-generate it run:
gcloud container clusters get-credentials "CLUSTER NAME"
This worked for me.
Add <br style="clear: both" />
after the last floated div worked for me.
Since you're using GNUmake, use a pattern rule for compiling object files:
$(OBJDIR)/%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
I have same issue , I fix it like this by adding xmlns:tools="http://schemas.android.com/tools"
to the top of mainfest file , and add tools:replace="android:icon"
to be look like
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" // add tools line here
package="yourpackage">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:replace="android:icon"> ///add this line
.....
</application>
</manifest>
Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).
You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
You need to use this function.
JSON.parse(yourJsonString);
And it will return the object / array that was contained within the string.
For security reasons, you can't move the mouse pointer with javascript, nor simulate a click with it.
What is it that you are trying to accomplish?
A zone transfer is the only way to be sure you have all the subdomain records. If the DNS is correctly configured you should not normally be able to perform an external zone transfer.
The scans.io project has a database of DNS records that can be downloaded and searched for subdomains. This requires downloading the 87GB of DNS data, alternatively you can try the online search of the data at https://hackertarget.com/find-dns-host-records/
delay() will not do the job. The problem with delay() is it's part of the animation system, and only applies to animation queues.
What if you want to wait before executing something outside of animation??
Use this:
window.setTimeout(function(){
// do whatever you want to do
}, 600);
What happens?: In this scenario it waits 600 miliseconds before executing the code specified within the curly braces.
This helped me a great deal once I figured it out and hope it will help you as well!
IMPORTANT NOTICE: 'window.setTimeout' happens asynchronously. Keep that in mind when writing your code!
I ran into this issue today. I found an solution on GitHub that does not require going to a later version of the beta.
Add the following script to your html:
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
This resolved the problem for me. For more details, you can follow the github issue here: https://github.com/angular/angular/issues/7144
SOLVING
Address already in use — bind(2)” 500 error in Ruby on Rails
Recently I tried running a Rails app on a production server. Not only did it not work, but it broke my localhost:3000 development server as well. Localhost would only load a blank white page or a 500 error.
To solve this, I used two quick commands. If these don’t return a result, you may need to look elsewhere for a solution, but this is a good quick fix.
lsof -wni tcp:3000
ruby 52179 rachelchervin 50u IPv6 0x...7aa3 0t0 TCP [::1]:hbci (LISTEN) ruby 52179 rachelchervin 51u IPv4 0x...c7bb 0t0 TCP 127.0.0.1:hbci (LISTEN) ruby 52180 rachelchervin 50u IPv6 0x...7aa3 0t0 TCP [::1]:hbci (LISTEN) ruby 52180 rachelchervin 51u IPv4 0x...c7bb 0t0 TCP 127.0.0.1:hbci (LISTEN)
This command shows all of my currently running processes and their PIDs (process IDs) on the 3000 port. Because there are existing running processes that did not close correctly, my new :3000 server can’t start, hence the 500 error.
kill 52179
kill 52180
rails s
I used the Linux kill command to manually stop the offending processes. If you have more than 4, simply use kill on any PIDs until the first command comes back blank. Then, try restarting your localhost:3000 server again. This will not damage your computer! It simply kills existing ruby processes on your localhost port. A new server will start these processes all over again. Good luck!
In my case Win 10. the file applicationHost.config is corrupted by VS 2012. And you can get the copy the history of this file under C:\inetpub\history. Then restart IIS and it works properly.
My experience is that there are many different csv formats. Specially how they handle escaping of quotes and delimiters within a field.
These are the variants I have ran into:
I have tried many of the existing csv parsers but there is not a single one that can handle the variants I have ran into. It is also difficult to find out from the documentation which escaping variants the parsers support.
In my projects I now use either the VB TextFieldParser or a custom splitter.
Try mono:
http://www.go-mono.com/mono-downloads/download.html
This download works on all versions of Windows XP, 2003, Vista and Windows 7.
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
i had the same issue. go to Sql Server Configuration management->SQL Server network config->protocols for 'servername' and check named pipes is enabled.
res.json
forces the argument to JSON. res.send
will take an non-json object or non-json array and send another type. For example:
This will return a JSON number.
res.json(100)
This will return a status code and issue a warning to use sendStatus.
res.send(100)
If your argument is not a JSON object or array (null,undefined,boolean,string), and you want to ensure it is sent as JSON, use res.json
.
Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.
The easiest way to handle this is to rename the column, copy the data over, then drop the original column:
alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;
alter table EVAPP_FEES add AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_OLD;
alter table EVAPP_FEES drop column AMOUNT_OLD;
If you really want to retain the column ordering, you can move the data twice instead:
alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);
update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;
update EVAPP_FEES set AMOUNT = null;
alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;
alter table EVAPP_FEES drop column AMOUNT_TEMP;
background-repeat:no-repeat;
background-position:center center;
Does not vertically center the background image when using a html 4.01 'STRICT' doctype.
Adding:
background-attachment: fixed;
Should fix the problem
(So Alexander is right)
it is now simply:
let serialQueue = DispatchQueue(label: "my serial queue")
the default is serial, to get concurrent, you use the optional attributes argument .concurrent
I got this error trying to test a solution using the following
string cn = "Data Source=[servername];Integrated Security=true;Initial Catalog=[dbname];";
The way I solved was: I had to open Visual Studio and run it under another account, because the account I was using to open was not my Admin account.
So if your problem is similar to mine: pin the VS to the task bar, then use Shift and Right Click to open the menu so you can open VS as another user.
//create a file handler by opening the file
$myTextFileHandler = @fopen("filelist.txt","r+");
//truncate the file to zero
//or you could have used the write method and written nothing to it
@ftruncate($myTextFileHandler, 0);
//use location header to go back to index.html
header("Location:index.html");
I don't exactly know where u want to show the result.
In Visual Studio you can use nuget to download the latest version. Just right click on the project and click 'Manage NuGet Packages' then search online for MySql.Data and install.
How much a stack can grow?
You can use a VM option named ss
to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M
to set the maximum of stack size to 1M.
Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss
set the size of the Java Stack in most cases.
For many JVMs, they put different default values for stack size on different platforms.
Can we limit this growth?
When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).
Does stack has some default minimum value or default maximum value?
As I said before, different VMs are different, and may change over versions. See here.
how does garbage collection work on stack?
Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.
This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.
Altough the question is for HTML, I would also additionally like to give info about how to auto-format your Javascript code for Sublime Text 2;
You can select all your code(ctrl + A) and use the in-app functionality, reindent(Edit
-> Line
-> Reindent
) or you can use JsFormat formatting plugin for Sublime Text 2
if you would like to have more customizable settings on how to format your code to addition to the Sublime Text's default tab/indent settings.
https://github.com/jdc0589/JsFormat
You can easily install JsFormat with using Package Control (Preferences
-> Package Control
) Open package control then type install, hit enter. Then type js format
and hit enter, you're done.
(The package controller will show the status of the installation with success and errors on the bottom left bar of Sublime
)
Add the following line to your key bindings (Preferences
-> Key Bindings User
)
{ "keys": ["ctrl+alt+2"], "command": "js_format"}
I'm using ctrl + alt + 2, you can change this shortcut key whatever you want to. So far, JsFormat
is a good plugin, worth to try it!
Hope this will help someone.
There are two ways to think about your phrase "application heap size available":
How much heap can my app use before a hard error is triggered? And
How much heap should my app use, given the constraints of the Android OS version and hardware of the user's device?
There is a different method for determining each of the above.
For item 1 above: maxMemory()
which can be invoked (e.g., in your main activity's onCreate()
method) as follows:
Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
Log.v("onCreate", "maxMemory:" + Long.toString(maxMemory));
This method tells you how many total bytes of heap your app is allowed to use.
For item 2 above: getMemoryClass()
which can be invoked as follows:
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
Log.v("onCreate", "memoryClass:" + Integer.toString(memoryClass));
This method tells you approximately how many megabytes of heap your app should use if it wants to be properly respectful of the limits of the present device, and of the rights of other apps to run without being repeatedly forced into the onStop()
/ onResume()
cycle as they are rudely flushed out of memory while your elephantine app takes a bath in the Android jacuzzi.
This distinction is not clearly documented, so far as I know, but I have tested this hypothesis on five different Android devices (see below) and have confirmed to my own satisfaction that this is a correct interpretation.
For a stock version of Android, maxMemory()
will typically return about the same number of megabytes as are indicated in getMemoryClass()
(i.e., approximately a million times the latter value).
The only situation (of which I am aware) for which the two methods can diverge is on a rooted device running an Android version such as CyanogenMod, which allows the user to manually select how large a heap size should be allowed for each app. In CM, for example, this option appears under "CyanogenMod settings" / "Performance" / "VM heap size".
NOTE: BE AWARE THAT SETTING THIS VALUE MANUALLY CAN MESS UP YOUR SYSTEM, ESPECIALLY if you select a smaller value than is normal for your device.
Here are my test results showing the values returned by maxMemory()
and getMemoryClass()
for four different devices running CyanogenMod, using two different (manually-set) heap values for each:
In addition to the above, I tested on a Novo7 Paladin tablet running Ice Cream Sandwich. This was essentially a stock version of ICS, except that I've rooted the tablet through a simple process that does not replace the entire OS, and in particular does not provide an interface that would allow the heap size to be manually adjusted.
For that device, here are the results:
Also (per Kishore in a comment below):
And (per akauppi's comment):
Per a comment from cmcromance:
And (per tencent's comments):
Other Devices
I haven't tested these two methods using the special android:largeHeap="true" manifest option available since Honeycomb, but thanks to cmcromance and tencent we do have some sample largeHeap values, as reported above.
My expectation (which seems to be supported by the largeHeap numbers above) would be that this option would have an effect similar to setting the heap manually via a rooted OS - i.e., it would raise the value of maxMemory()
while leaving getMemoryClass()
alone. There is another method, getLargeMemoryClass(), that indicates how much memory is allowable for an app using the largeHeap setting. The documentation for getLargeMemoryClass() states, "most applications should not need this amount of memory, and should instead stay with the getMemoryClass() limit."
If I've guessed correctly, then using that option would have the same benefits (and perils) as would using the space made available by a user who has upped the heap via a rooted OS (i.e., if your app uses the additional memory, it probably will not play as nicely with whatever other apps the user is running at the same time).
Note that the memory class apparently need not be a multiple of 8MB.
We can see from the above that the getMemoryClass()
result is unchanging for a given device/OS configuration, while the maxMemory() value changes when the heap is set differently by the user.
My own practical experience is that on the G1 (which has a memory class of 16), if I manually select 24MB as the heap size, I can run without erroring even when my memory usage is allowed to drift up toward 20MB (presumably it could go as high as 24MB, although I haven't tried this). But other similarly large-ish apps may get flushed from memory as a result of my own app's pigginess. And, conversely, my app may get flushed from memory if these other high-maintenance apps are brought to the foreground by the user.
So, you cannot go over the amount of memory specified by maxMemory()
. And, you should try to stay within the limits specified by getMemoryClass()
. One way to do that, if all else fails, might be to limit functionality for such devices in a way that conserves memory.
Finally, if you do plan to go over the number of megabytes specified in getMemoryClass()
, my advice would be to work long and hard on the saving and restoring of your app's state, so that the user's experience is virtually uninterrupted if an onStop()
/ onResume()
cycle occurs.
In my case, for reasons of performance I'm limiting my app to devices running 2.2 and above, and that means that almost all devices running my app will have a memoryClass of 24 or higher. So I can design to occupy up to 20MB of heap and feel pretty confident that my app will play nice with the other apps the user may be running at the same time.
But there will always be a few rooted users who have loaded a 2.2 or above version of Android onto an older device (e.g., a G1). When you encounter such a configuration, ideally, you ought to pare down your memory use, even if maxMemory()
is telling you that you can go much higher than the 16MB that getMemoryClass()
is telling you that you should be targeting. And if you cannot reliably ensure that your app will live within that budget, then at least make sure that onStop()
/ onResume()
works seamlessly.
getMemoryClass()
, as indicated by Diane Hackborn (hackbod) above, is only available back to API level 5 (Android 2.0), and so, as she advises, you can assume that the physical hardware of any device running an earlier version of the OS is designed to optimally support apps occupying a heap space of no more than 16MB.
By contrast, maxMemory()
, according to the documentation, is available all the way back to API level 1. maxMemory()
, on a pre-2.0 version, will probably return a 16MB value, but I do see that in my (much later) CyanogenMod versions the user can select a heap value as low as 12MB, which would presumably result in a lower heap limit, and so I would suggest that you continue to test the maxMemory()
value, even for versions of the OS prior to 2.0. You might even have to refuse to run in the unlikely event that this value is set even lower than 16MB, if you need to have more than maxMemory()
indicates is allowed.
1) the django csrf check (assuming you're sending one) is here
2) In my case, settings.CSRF_HEADER_NAME
was set to 'HTTP_X_CSRFTOKEN' and my AJAX call was sending a header named 'HTTP_X_CSRF_TOKEN' so stuff wasn't working. I could either change it in the AJAX call, or django setting.
3) If you opt to change it server-side, find your install location of django and throw a breakpoint in the csrf middleware
.f you're using virtualenv
, it'll be something like: ~/.envs/my-project/lib/python2.7/site-packages/django/middleware/csrf.py
import ipdb; ipdb.set_trace() # breakpoint!!
if request_csrf_token == "":
# Fall back to X-CSRFToken, to make things easier for AJAX,
# and possible for PUT/DELETE.
request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')
Then, make sure the csrf
token is correctly sourced from request.META
4) If you need to change your header, etc - change that variable in your settings file
You may want to create a subRepeater.
<asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
<ItemTemplate>
<span><%# Eval("Name") %></span>
</ItemTemplate>
</asp:Repeater>
You can also cast your fields
<%# ((ArrayFields)Container.DataItem).Fields[0].Name %>
Finally you could do a little CSV Function and write out your fields with a function
<%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>
public string GetAsCsv(IEnumerable<Fields> fields)
{
var builder = new StringBuilder();
foreach(var f in fields)
{
builder.Append(f);
builder.Append(",");
}
builder.Remove(builder.Length - 1);
return builder.ToString();
}
^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$
First, open a terminal session and run:
cd /usr/local/
git status
to see if Homebrew is clean.
If it's dirty, run:
git reset --hard && git clean -df
then
brew doctor
brew update
If it's still broken, try this in your session:
sudo rm /System/Library/Frameworks/Ruby.framework/Versions/Current
sudo ln -s /System/Library/Frameworks/Ruby.framework/Versions/1.8 /System/Library/Frameworks/Ruby.framework/Versions/Current
This will force Homebrew to use Ruby 1.8 from the system's installation.
The approved answer from @jbochi does not work for me. The str() function call raises an exception because it cannot encode the non-ascii characters in the BeautifulSoup element. Here is a more succinct way to filter the example web page to visible text.
html = open('21storm.html').read()
soup = BeautifulSoup(html)
[s.extract() for s in soup(['style', 'script', '[document]', 'head', 'title'])]
visible_text = soup.getText()
NERDTree opens up in another window. That split view you're seeing? They're called windows in vim parlance. All the window commands start with CTRL-W. To move from adjacent windows that are left and right of one another, you can change focus to the window to the left of your current window with CTRL-w h, and move focus to the right with CTRL-w l. Likewise, CTRL-w j and CTRL-w k will move you between horizontally split windows (i.e., one window is above the other). There's a lot more you can do with windows as described here.
You can also use the :NERDTreeToggle command to make your tree open and close. I usually bind that do t.
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
Code folding by regions has arrived with v1.17. Folding by regions documentation. And v1.19 and 1.23.
[Generally you can add a space, for example // region and // endregion
to //region and //endregion
and it will also work.]
TypeScript/JavaScript: //#region and //#endregion or // #region and // #endregion
C#: #region and #endregion
C/C++: #pragma region and #pragma endregion
F#: //#region and //#endregion
PowerShell: #region and #endregion
Python: #region and #endregion
VB: #Region and #End Region
PHP: #region and #endregion
Bat: ::#region and ::#endregion or REM #region and REM #endregion
Markdown: <!-- #region --> and <!-- #endregion -->
Golang //region and //endregion or //#region and //#endregion
Java //#region and //#endregion
CSS/SCSS/Less: /* #region */ and /* #endregion */ or /*#region*/ and /*#endregion*/
SCSS/Less: // #region and // #endregion
Go: // region, // endregion and // #region, // #endregion
shellscript: # region and # endregion
Perl5 #region and #endregion or =pod and =cut`
Important: If you don't see your language in the list::
Each language also has snippets available for the markers. Type '#' and invoke code completion to see them. To have region markers configured for your language, contact the language extension provider.
So type #
and then Ctrl+Space to see the region markers for any language.
A string-oriented alternative, that uses an array:
spec=(IGNORE REPLACE)
for p in {13..15}; do
echo "$p: ${spec[p==14]}";
done
which outputs:
13: IGNORE
14: REPLACE
15: IGNORE
Try ajaxsubmit library. It does ajax submition as well as validation via ajax.
Also configuration is very flexible to support any kind of UI.
Live demo available with js, css and html examples.
Two Methods for Passing Multiple route params in Angular
Method-1
In app.module.ts
Set path as component2.
imports: [
RouterModule.forRoot(
[ {path: 'component2/:id1/:id2', component: MyComp2}])
]
Call router to naviagte to MyComp2 with multiple params id1 and id2.
export class MyComp1 {
onClick(){
this._router.navigate( ['component2', "id1","id2"]);
}
}
Method-2
In app.module.ts
Set path as component2.
imports: [
RouterModule.forRoot(
[ {path: 'component2', component: MyComp2}])
]
Call router to naviagte to MyComp2 with multiple params id1 and id2.
export class MyComp1 {
onClick(){
this._router.navigate( ['component2', {id1: "id1 Value", id2:
"id2 Value"}]);
}
}
Others have pointed out the deleteCharAt
method, but here's another alternative approach:
String prefix = "";
for (String serverId : serverIds) {
sb.append(prefix);
prefix = ",";
sb.append(serverId);
}
Alternatively, use the Joiner
class from Guava :)
As of Java 8, StringJoiner
is part of the standard JRE.
This problem occurs because the Web site does not have the Directory Browsing
feature enabled, and the default document is not configured. To resolve this problem, use one of the following methods. To resolve this problem, I followed the steps in Method 1 as mentioned in the MS Support page and its the recommended method.
Method 1: Enable the Directory Browsing feature in IIS (Recommended)
Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
In the Features view, double-click Directory Browsing.
In the Actions pane, click Enable.
If that does not work for, you might be having different problem than just a Directory listing issue. So follow the below step,
Method 2: Add a default document
To resolve this problem, follow these steps:
Method 3: Enable the Directory Browsing feature in IIS Express
Note This method is for the web developers who experience the issue when they use IIS Express.
Follow these steps:
Open a command prompt, and then go to the IIS Express folder on your computer.
For example, go to the following folder in a command prompt:
C:\Program Files\IIS Express
Type the following command, and then press Enter:
appcmd set config /section:system.webServer/directoryBrowse /enabled:true
A few years late, but I have a solution for the most recent version of WordPress, which has this same issue (WordPress-generated .htaccess files break sites, reuslting in 403 Forbidden error messages). Here's that it looks like when WordPress creates it:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
The problem is that the conditional doesn't work. It doesn't work because the module it's looking for isn't .c
, it's .so
. I think this is a platform-specific, or configuration-specific issue, where Mac OS and Lunix Apache installations are set up for .so
AKA 'shared-object' modules. Looking for a .c
module shouldn't break the conditional, I think that's a bug, but it's the issue.
Simply change the mod_rewrite.c
to mod_rewrite.so
and you're all set to go!
# BEGIN WordPress
<IfModule mod_rewrite.so>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.
Upgrade to PostgreSQL 9.5 or greater. If (not) exists was introduced in version 9.5.
By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).