I usually put these lines at the beginning of my stored procedure, and then at the end.
It is an "exists" check for #temp tables.
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
begin
drop table #MyCoolTempTable
end
Full Example:
CREATE PROCEDURE [dbo].[uspTempTableSuperSafeExample]
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyCoolTempTable
END
CREATE TABLE #MyCoolTempTable (
MyCoolTempTableKey INT IDENTITY(1,1),
MyValue VARCHAR(128)
)
INSERT INTO #MyCoolTempTable (MyValue)
SELECT LEFT(@@VERSION, 128)
UNION ALL SELECT TOP 10 LEFT(name, 128) from sysobjects
SELECT MyCoolTempTableKey, MyValue FROM #MyCoolTempTable
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyCoolTempTable
END
SET NOCOUNT OFF;
END
GO
You don't need the CELL() part of your formulas:
=INDIRECT(ADDRESS(B1,B2))
or
=OFFSET($A$1, B1-1,B2-1)
will both work. Note that both INDIRECT
and OFFSET
are volatile functions. Volatile functions can slow down calculation because they are calculated at every single recalculation.
for the above problem ur password in the system should matches with the password u have passed in the program because when u run the program it checks system's password as u have given root as a user so gives u an error and at the same time the record is not deleted from the database.
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
class Delete
{
public static void main(String []k)
{
String url="jdbc:mysql://localhost:3306/student";
String user="root";
String pass="jacob234";
try
{
Connection myConnection=DriverManager.getConnection(url,user,pass);
Statement myStatement=myConnection.createStatement();
String deleteQuery="delete from students where id=2";
myStatement.executeUpdate(deleteQuery);
System.out.println("delete completed");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
Keep ur system password as jacob234 and then run the code.
its kind of hacky but it works well-ish
function close_frame(){
if(!window.should_close){
window.should_close=1;
}else if(window.should_close==1){
location.reload();
//or iframe hide or whatever
}
}
<iframe src="iframe_index.php" onload="close_frame()"></iframe>
then inside the frame
$('#close_modal_main').click(function(){
window.location = 'iframe_index.php?close=1';
});
and if you want to get fancy through a
if(isset($_GET['close'])){
die;
}
at the top of your frame page to make that reload unnoticeable
so basically the first time the frame loads it doesnt hide itself but the next time it loads itll call the onload function and the parent will have a the window var causing the frame to close
Just an update with Java Generics.
You could create an utility method to retrieve an optional value of any Java type from a given ResultSet, previously casted.
Unfortunately, getObject(columnName, Class) does not return null, but the default value for given Java type, so 2 calls are required
public <T> T getOptionalValue(final ResultSet rs, final String columnName, final Class<T> clazz) throws SQLException {
final T value = rs.getObject(columnName, clazz);
return rs.wasNull() ? null : value;
}
In this example, your code could look like below:
final Integer columnValue = getOptionalValue(rs, Integer.class);
if (columnValue == null) {
//null handling
} else {
//use int value of columnValue with autoboxing
}
Happy to get feedback
For VS 2015 & VS 2017: Right-click the IIS Express system tray icon (when running the application), and select "Show all applications":
Then, select the relevant application and click the applicationhost.config file path:
Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:
JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);
According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
return font.deriveFont(12f);
The link provided in the accepted answer shows a nice way to implement the pub/sub system using jQuery, but I found the code somewhat difficult to read, so here is my simplified version of the code:
$(document).on('testEvent', function(e, eventInfo) {
subscribers = $('.subscribers-testEvent');
subscribers.trigger('testEventHandler', [eventInfo]);
});
$('#myButton').on('click', function() {
$(document).trigger('testEvent', [1011]);
});
$('#notifier1').on('testEventHandler', function(e, eventInfo) {
alert('(notifier1)The value of eventInfo is: ' + eventInfo);
});
$('#notifier2').on('testEventHandler', function(e, eventInfo) {
alert('(notifier2)The value of eventInfo is: ' + eventInfo);
});
There's the openpxyl package:
>>> from openpyxl import load_workbook
>>> wb2 = load_workbook('test.xlsx')
>>> print wb2.get_sheet_names()
['Sheet2', 'New Title', 'Sheet1']
>>> worksheet1 = wb2['Sheet1'] # one way to load a worksheet
>>> worksheet2 = wb2.get_sheet_by_name('Sheet2') # another way to load a worksheet
>>> print(worksheet1['D18'].value)
3
>>> for row in worksheet1.iter_rows():
>>> print row[0].value()
I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.
If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.
- Rich ToolTips rather than text
- WPF context menus and popups
- Command support and routed events
- Flexible data binding
- Rich balloon messages rather than the default messages provides by the OS
Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.
ul > li > a
selects only the direct children. In this case only the first level <a>
of the first level <li>
inside the <ul>
will be selected.
ul li a
on the other hand will select ALL <a>
-s in ALL <li>
-s in the unordered list
Example of ul > li
ul > li.bg {_x000D_
background: red;_x000D_
}
_x000D_
<ul>_x000D_
<li class="bg">affected</li>_x000D_
<li class="bg">affected</li> _x000D_
<li>_x000D_
<ol>_x000D_
<li class="bg">NOT affected</li>_x000D_
<li class="bg">NOT affected</li>_x000D_
</ol>_x000D_
</li>_x000D_
</ul>
_x000D_
if you'd be using ul li
- ALL of the li
-s would be affected
UPDATE The order of more to less efficient CSS selectors goes thus:
#header
.promo
div
h2 + p
li > ul
ul a
*
[type="text"]
a:hover
So your better bet is to use the children
selector instead of just descendant
. However the difference on a regular page (without tens of thousands elements to go through) might be absolutely negligible.
make it simple
private void dataGridView1_cellformatting(object sender,DataGridViewCellFormattingEventArgs e)
{
var amount = (int)e.Value;
// return if rowCount = 0
if (this.dataGridView1.Rows.Count == 0)
return;
if (amount > 0)
e.CellStyle.BackColor = Color.Green;
else
e.CellStyle.BackColor = Color.Red;
}
take a look cell formatting
Like it's already mentioned, I would highly recommend using regular expression (in System.Text) to get this kind of job done.
In combo with a solid tool like RegexBuddy, you are looking at handling any complex text record parsing situations, as well as getting results quickly. The tool makes it real easy.
Hope that helps.
Do you have a _ViewStart.cshtml
in this directory? I had the same problem you're having when I tried using _ViewStart. Then I renamed it _mydefaultview, moved it to the Views/Shared
directory, and switched to specifying no view in cshtml files where I don't want it, and specifying _mydefaultview for the rest. Don't know why this was necessary, but it worked.
> show tables
It gives the same result as Cameron's answer.
Instead for rewriting all my path code as suggested, I changed the working directory:
if getattr(sys, 'frozen', False):
os.chdir(sys._MEIPASS)
Just add those two lines at the beginning of your code, you can leave the rest as is.
Hope this helps, with Serverless framework you can do something like this:
plugins:
- serverless-webpack
custom:
webpackIncludeModules:
forceInclude:
- <your package name> (for example: node-fetch)
2. Then create your Lambda function, deploy it by serverless deploy
, the package that included in serverless.yml will be there for you.
For more information about serverless: https://serverless.com/framework/docs/providers/aws/guide/quick-start/
If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:
from FILE NAME import FUNCTION NAME
Note - the parts in capital letters are where you type the file name and function name.
Now you just use your function however it was meant to be.
Example:
FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py
def choose(a):
from random import randint
b = randint(0, len(a) - 1)
c = a[b]
return(c)
SCRIPT USING FUNCTION - saved wherever
from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))
OUTPUT WILL BE DOG, CAT, OR CHICKEN
Hoped this helped, now you can create function packs for download!
--------------------------------This is for Python 2.7-------------------------------------
Instead of this:
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
Try this:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search] )
See the MySQLdb documentation. The reasoning is that execute
's second parameter represents a list of the objects to be converted, because you could have an arbitrary number of objects in a parameterized query. In this case, you have only one, but it still needs to be an iterable (a tuple instead of a list would also be fine).
I know this is an old question, but I think this is the definitive answer.
listViewRamos.Items[i].Focused = true;
listViewRamos.Items[i].Selected = true;
listViewRemos.Items[i].EnsureVisible();
If there is a chance the control does not have the focus but you want to force the focus to the control, then you can add the following line.
listViewRamos.Select();
Why Microsoft didn't just add a SelectItem()
method that does all this for you is beyond me.
A small variation of Sean's answer:
<import resource="classpath*:spring-config.xml" />
With the asterisk in order to spring search files 'spring-config.xml' anywhere in the classpath.
Another reference: Divide Spring configuration across multiple projects
Use this one:
Get-ChildItem -Path \\server\share\folder\ -Recurse -Force | where {$_.Attributes -like '*Directory*'} | Export-Csv -Path C:\Temp\Export.csv -Encoding "Unicode" -Delimiter ";"
See also this answer in order to switch the mode conveniently.
Citation:
I use this feature often enough that I add a custom button to the command bar.
Click on the Add or Remove -> Customize
Click on the Commands tab
Select Edit|Advanced from the list
Find Toggle Word Wrap and drag it onto your bar
Use number formatter
Swift 4.x
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let s = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
guard !s.isEmpty else { return true }
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .none
return numberFormatter.number(from: s)?.intValue != nil
}
The LINQ to SQL return object were implementing IQueryable
interface. So for Select
method predicate parameter you should only supply single lambda expression without body.
This is because LINQ for SQL code is not execute inside program rather than on remote side like SQL server or others. This lazy loading execution type were achieve by implementing IQueryable where its expect delegate is being wrapped in Expression type class like below.
Expression<Func<TParam,TResult>>
Expression tree do not support lambda expression with body and its only support single line lambda expression like var id = cols.Select( col => col.id );
So if you try the following code won't works.
Expression<Func<int,int>> function = x => {
return x * 2;
}
The following will works as per expected.
Expression<Func<int,int>> function = x => x * 2;
First of all you need to understand that final output of both the statements will be same i.e. to remove all the spaces from given string.
However x.replaceAll("\\s+", "");
will be more efficient way of trimming spaces (if string can have multiple contiguous spaces) because of potentially less no of replacements due the to fact that regex \\s+
matches 1 or more spaces at once and replaces them with empty string.
So even though you get the same output from both it is better to use:
x.replaceAll("\\s+", "");
All the current answers clobber the non-writing permissions: they make the file readable-but-not-executable for everybody. Granted, this is because the initial question asked for 444
permissions -- but we can do better!
Here's a solution that leaves all the individual "read" and "execute" bits untouched. I wrote verbose code to make it easy to understand; you can make it more terse if you like.
import os
import stat
def remove_write_permissions(path):
"""Remove write permissions from this path, while keeping all other permissions intact.
Params:
path: The path whose permissions to alter.
"""
NO_USER_WRITING = ~stat.S_IWUSR
NO_GROUP_WRITING = ~stat.S_IWGRP
NO_OTHER_WRITING = ~stat.S_IWOTH
NO_WRITING = NO_USER_WRITING & NO_GROUP_WRITING & NO_OTHER_WRITING
current_permissions = stat.S_IMODE(os.lstat(path).st_mode)
os.chmod(path, current_permissions & NO_WRITING)
Why does this work?
As John La Rooy pointed out,stat.S_IWUSR
basically means "the bitmask for the user's write permissions". We want to set the corresponding permission bit to 0. To do that, we need the exact opposite bitmask (i.e., one with a 0 in that location, and 1's everywhere else). The ~
operator, which flips all the bits, gives us exactly that. If we apply this to any variable via the "bitwise and" operator (&
), it will zero out the corresponding bit.
We need to repeat this logic with the "group" and "other" permission bits, too. Here we can save some time by just &
'ing them all together (forming the NO_WRITING
bit constant).
The last step is to get the current file's permissions, and actually perform the bitwise-and operation.
One is an interface (CharSequence
) while other is a concrete implementation of that interface (String
).
CharSequence animal = "cat" // `String` object presented as the interface `CharSequence`.
Just like ArrayList
is a List
, and HashMap
is a Map
, so too String
is a CharSequence
.
As an interface, normally the CharSequence
would be more commonly seen than String
, but some twisted history resulted in the interface being defined years after the implementation. So in older APIs we often see String
while in newer APIs we tend to see CharSequence
used to define arguments and return types.
Nowadays we know that generally an API/framework should focus on exporting interfaces primarily and concrete classes secondarily. But we did not always know this lesson so well.
The String
class came first in Java. Only later did they place a front-facing interface, CharSequence
.
A little history might help with understanding.
In its early days, Java was rushed to market a bit ahead of its time, due to the Internet/Web mania animating the industry. Some libraries were not as well thought-through as they should have been. String handling was one of those areas.
Also, Java was one of the earliest production-oriented non-academic Object-Oriented Programming (OOP) environments. The only successful real-world rubber-meets-the-road implementations of OOP before that was some limited versions of SmallTalk, then Objective-C with NeXTSTEP/OpenStep. So, many practical lessons were yet to be learned.
Java started with the String
class and StringBuffer
class. But those two classes were unrelated, not tied to each other by inheritance nor interface. Later, the Java team recognized that there should have been a unifying tie between string-related implementations to make them interchangeable. In Java 4 the team added the CharSequence
interface and retroactively implemented that interface on String and String Buffer, as well as adding another implementation CharBuffer
. Later in Java 5 they added StringBuilder
, basically a unsynchronized and therefore somewhat faster version of StringBuffer
.
So these string-oriented classes are a bit of a mess, and a little confusing to learn about. Many libraries and interfaces were built to take and return String
objects. Nowadays such libraries should generally be built to expect CharSequence
. But (a) String
seems to still dominate the mindspace, and (b) there may be some subtle technical issues when mixing the various CharSequence
implementations. With the 20/20 vision of hindsight we can see that all this string stuff could have been better handled, but here we are.
Ideally Java would have started with an interface and/or superclass that would be used in many places where we now use String
, just as we use the Collection
or List
interfaces in place of the ArrayList
or LinkedList
implementations.
The key difference about CharSequence
is that it is an interface, not an implementation. That means you cannot directly instantiate a CharSequence
. Rather you instantiate one of the classes that implements that interface.
For example, here we have x
that looks like a CharSequence
but underneath is actually a StringBuilder
object.
CharSequence x = new StringBuilder( "dog" ); // Looks like a `CharSequence` but is actually a `StringBuilder` instance.
This becomes less obvious when using a String literal. Keep in mind that when you see source code with just quote marks around characters, the compiler is translating that into a String object.
CharSequence y = "cat"; // Looks like a `CharSequence` but is actually a `String` instance.
There are some subtle differences between "cat"
and new String("cat")
as discussed in this other Question, but are irrelevant here.
This class diagram may help to guide you. I noted the version of Java in which they appeared to demonstrate how much change has churned through these classes and interfaces.
Other than adding more Unicode characters including a multitude of emoji, in recent years not much has changed in Java for working with text. Until text blocks.
Text blocks are a new way of better handling the tedium of string literals with multiple lines or character-escaping. This would make writing embedded code strings such as HTML, XML, SQL, or JSON much more convenient.
To quote JEP 378:
A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.
The text blocks feature does not introduce a new data type. Text blocks are merely a new syntax for writing a String
literal. A text block produces a String
object, just like the conventional literal syntax. A text block produces a String
object, which is also a CharSequence
object, as discussed above.
To quote JSR 378 again…
Using "one-dimensional" string literals.
String query = "SELECT \"EMP_ID\", \"LAST_NAME\" FROM \"EMPLOYEE_TB\"\n" +
"WHERE \"CITY\" = 'INDIANAPOLIS'\n" +
"ORDER BY \"EMP_ID\", \"LAST_NAME\";\n";
Using a "two-dimensional" block of text
String query = """
SELECT "EMP_ID", "LAST_NAME" FROM "EMPLOYEE_TB"
WHERE "CITY" = 'INDIANAPOLIS'
ORDER BY "EMP_ID", "LAST_NAME";
""";
Text blocks are found in Java 15 and later, per JEP 378: Text Blocks.
First previewed in Java 13, under JEP 355: Text Blocks (Preview). Then previewed again in Java 14 under JEP 368: Text Blocks (Second Preview).
This effort was preceded by JEP 326: Raw String Literals (Preview). The concepts were reworked to produce the Text Blocks feature instead.
GNU mailutils's 'mail' command doesn't let you do this (easily at least). But If you install 'heirloom-mailx', its mail command (mailx) has the '-r' option to override the default '$USER@$HOSTNAME' from field.
echo "Hello there" | mail -s "testing" -r [email protected] [email protected]
Works for 'mailx' but not 'mail'.
$ ls -l /usr/bin/mail lrwxrwxrwx 1 root root 22 2010-12-23 08:33 /usr/bin/mail -> /etc/alternatives/mail $ ls -l /etc/alternatives/mail lrwxrwxrwx 1 root root 23 2010-12-23 08:33 /etc/alternatives/mail -> /usr/bin/heirloom-mailx
For those running SDK Manager in Eclipse, selecting "Run As Administrator" while starting Eclipse.exe helps.
I had the same problem on Windows.
The source of the problem is simple, it is access permission on folders and files.
In your project folder, you need
After that, error "Error: EPERM: operation not permitted, unlink" will no longer be displayed.
Remember to reactivate the firewall and antivirus if necessary.
Just pass in the current Context to the Adapter constructor and store it as a field. Then inside the onClick you can use that context to call startActivity().
pseudo-code
public class MyAdapter extends Adapter {
private Context context;
public MyAdapter(Context context) {
this.context = context;
}
public View getView(...){
View v;
v.setOnClickListener(new OnClickListener() {
void onClick() {
context.startActivity(...);
}
});
}
}
According to the documentation since Symfony 2.1 simply use this shortcut :
$user = $this->getUser();
The above is still working on Symfony 3.2 and is a shortcut for this :
$user = $this->get('security.token_storage')->getToken()->getUser();
The
security.token_storage
service was introduced in Symfony 2.6. Prior to Symfony 2.6, you had to use thegetToken()
method of thesecurity.context
service.
Example : And if you want directly the username :
$username = $this->getUser()->getUsername();
The user will be an object and the class of that object will depend on your user provider.
CoreUtils referred to in other posts does NOT show the real implementation of most of the functionality which I think you seek. In most cases it provides front-ends for the actual functions that retrieve the data, which can be found here:
It is build upon Gnulib with the actual source code in the lib-subdirectory
One issue might be Service class is not enabled in AndroidManifest file. Please check it as well.
<service
android:name=".AudioRecorderService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="microphone" />
You used wrong letter case for year in line:
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
Should be:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
With this change everything is working as expected.
First import and run django.setup() before importing any models
All the above answers are good but there is a simple mistake a person could do is that (In fact in my case it was).
I imported Django model from my app before calling django.setup()
. so proper way is to do...
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings')
import django
django.setup()
then any other import like
from faker import Faker
import random
# import models only after calling django.setup()
from first_app.models import Webpage, Topic, AccessRecord
Set the seed using srand(). Also, you're not specifying the max value in rand(), so it's using RAND_MAX. I'm not sure if it's actually 10000... why not just specify it. Although, we don't know what your "expected results" are. It's a random number generator. What are you expecting, and what are you seeing?
As noted in another comment, SA() isn't returning anything explicitly.
http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html http://www.thinkage.ca/english/gcos/expl/c/lib/rand.html
Edit:
From Generating random number between [-1, 1] in C?
((float)rand())/RAND_MAX
returns a floating-point number in [0,1]
If you want to filter out extensions from the output of another command e.g. "git":
files=$(git diff --name-only --diff-filter=d origin/master... | grep -E '\.cpp$|\.h$')
for file in $files; do
echo "$file"
done
Consider these filenames:
C:\temp\file.txt
- This is a path, an absolute path, and a canonical path.
.\file.txt
- This is a path. It's neither an absolute path nor a canonical path.
C:\temp\myapp\bin\..\\..\file.txt
- This is a path and an absolute path. It's not a canonical path.
A canonical path is always an absolute path.
Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. ./file.txt
becomes c:/temp/file.txt
). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\
and resolving symlinks (on unixes).
Also note the following example with nio.Paths:
String canonical_path_string = "C:\\Windows\\System32\\";
String absolute_path_string = "C:\\Windows\\System32\\drivers\\..\\";
System.out.println(Paths.get(canonical_path_string).getParent());
System.out.println(Paths.get(absolute_path_string).getParent());
While both paths refer to the same location, the output will be quite different:
C:\Windows
C:\Windows\System32\drivers
I didn't want to open another threat so ill post my problem here
Ajax wont forward value to controller, and i just cant find an error :(
-JS
<script>
$(document).ready(function () {
$("#sMarka").change(function () {
var markaId = $(this).val();
alert(markaId);
debugger
$.ajax({
type:"POST",
url:"@Url.Action("VratiModele")",
dataType: "html",
data: { "markaId": markaId },
success: function (model) {
debugger
$("#sModel").empty();
$("#sModel").append(model);
}
});
});
});
</script>
--controller
public IActionResult VratiModele(int markaId = 0)
{
if (markaId != 0)
{
List<Model> listaModela = db.Modeli.Where(m => m.MarkaId == markaId).ToList();
ViewBag.ModelVozila = new SelectList(listaModela, "ModelId", "Naziv");
}
else
{
ViewBag.Greska = markaId.ToString();
}
return PartialView();
}
Try this example
Html
<div class="testimonial" data-index="1">
Testimonial 1
</div>
<div class="testimonial" data-index="2">
Testimonial 2
</div>
<div class="testimonial" data-index="3">
Testimonial 3
</div>
<div class="testimonial" data-index="4">
Testimonial 4
</div>
<div class="testimonial" data-index="5">
Testimonial 5
</div>
When we want to access those divs
which has data-index
greater than 2
then we need this jquery.
$('div[class="testimonial"]').each(function(index,item){
if(parseInt($(item).data('index'))>2){
$(item).html('Testimonial '+(index+1)+' by each loop');
}
});
This is another functional lib with which you may use map: http://code.google.com/p/totallylazy/
sequence(1, 2).map(toString); // lazily returns "1", "2"
SELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active';
Since pg_stat_activity
contains connection statistics of all databases having any state, either idle
or active
, database name and connection state should be included in the query to get the desired output.
Heroes of Might and Magic V used modified Silent Storm engine. I think you can find many good engines listed in wikipedia: Lua-scriptable game engines
Use DECIMAL(8,6)
for latitude (90 to -90 degrees) and DECIMAL(9,6)
for longitude (180 to -180 degrees). 6 decimal places is fine for most applications. Both should be "signed" to allow for negative values.
Create a Pivot Table. It has these features and many more.
If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.
If you use it in a database, this is a good way:
Set the ip field in database to varchar(250), and then use this:
$theip = $_SERVER["REMOTE_ADDR"];
if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$theip .= '('.$_SERVER["HTTP_X_FORWARDED_FOR"].')';
}
if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
$theip .= '('.$_SERVER["HTTP_CLIENT_IP"].')';
}
$realip = substr($theip, 0, 250);
Then you just check $realip against the database ip field
You are trying to set int value to TextView
so you are getting this issue.
To solve this try below one option
option 1:
tv.setText(no+"");
Option2:
tv.setText(String.valueOf(no));
Modern processors are too fast to register the running time. Hence it may return zero. In this case, the time you started and ended is too small and therefore both the times are the same after round of.
It's not a good way, but for me it seems the most simplest.
Add an anchor tag which contains the modal data-target and data-toggle, have an id associated with it. (Can be added mostly anywhere in the html view)
<a href="" data-toggle="modal" data-target="#myModal" id="myModalShower"></a>
Now,
Inside the angular controller, from where you want to trigger the modal just use
angular.element('#myModalShower').trigger('click');
This will mimic a click to the button based on the angular code and the modal will appear.
According to Apple documents for swift 4.1 you can use this struct so easily to create a 2D array:
Code sample:
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT
time! if it does not get any signal it throw exception! It means that time expired!
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class SocketTest extends Thread {
private ServerSocket serverSocket;
public SocketTest() throws IOException {
serverSocket = new ServerSocket(8008);
serverSocket.setSoTimeout(10000);
}
public void run() {
while (true) {
try {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket client = serverSocket.accept();
System.out.println("Just connected to " + client.getRemoteSocketAddress());
client.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
try {
Thread t = new SocketTest();
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
after digging jQueryUI.com for datepicker, here's my conclusion and answer to your question.
First, I would say no to your question. You can't use jQueryUI datepicker for picking month and year only. It is not supported. It has no callback function for that.
But you can hack it to display only month and and year by using css to hide the days, etc. And I think won't make sense still cause you need the dates to be click in order to pick a date.
I can say you just have to use another datepicker. Like what Roger suggested.
The accepted answer is perfect, however if you want to do it from xml, you can use android:scaleType="fitXY"
Starting simple, with no HTML:
foreach($database as $file) {
echo $file['filename'] . ' at ' . $file['filepath'];
}
And you can otherwise manipulate the fields in the foreach.
Here are a few ways to create a list with N of continuous natural numbers starting from 1.
1 range:
def numbers(n):
return range(1, n+1);
2 List Comprehensions:
def numbers(n):
return [i for i in range(1, n+1)]
You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!
My solution is trigger from a real touch event in a prior menu. They don't force you to use a specific player interface of course. For my purposes, this works well. If you don't have an existing interface to use, afaik you're buggered. Maybe you could try tilt events or something...
make sure your doSomething function is not static.
Your question is specifically about how to get Applescript to do what you want. But, for the particular example described, you might want to look into 'expect' as a solution.
The simple way of doing this would be (assuming your list is in 'l'):
>>> counter = {}
>>> for i in l: counter[i] = counter.get(i, 0) + 1
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]
Complete sample:
>>> l = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
>>> counter = {}
>>> for i in l: counter[i] = counter.get(i, 0) + 1
...
>>> counter
{'and': 3, '': 1, 'merry': 1, 'rise.': 1, 'small;': 1, 'Moon': 1, 'cheerful': 1, 'bright': 1, 'Cats': 5, 'are': 3, 'have': 2, 'bright,': 1, 'for': 1, 'their': 1, 'rather': 1, 'when': 1, 'to': 3, 'airs': 1, 'black': 2, 'They': 1, 'practise': 1, 'caterwaul.': 1, 'pleasant': 1, 'hear': 1, 'they': 1, 'white,': 1, 'wait': 1, 'And': 2, 'like': 1, 'Jellicle': 6, 'eyes;': 1, 'the': 1, 'faces,': 1, 'graces': 1}
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]
With simple I mean working in nearly every version of python.
if you don't understand some of the functions used in this sample, you can always do this in the interpreter (after pasting the code above):
>>> help(counter.get)
>>> help(sorted)
I have tried this code and It's working fine in my case.
DELETE FROM NG_USR_0_CLIENT_GRID_NEW WHERE rowid IN
( SELECT rowid FROM
(
SELECT wi_name, relationship, ROW_NUMBER() OVER (ORDER BY rowid DESC) RN
FROM NG_USR_0_CLIENT_GRID_NEW
WHERE wi_name = 'NB-0000001385-Process'
)
WHERE RN=2
);
I see that you've tagged this question with the google-spreadsheet-api
tag. So by "drop-down" do you mean Google App Script's ListBox? If so, you may toggle a user's ability to select multiple items from the ListBox with a simple true/false value.
Here's an example:
`var lb = app.createListBox(true).setId('myId').setName('myLbName');`
Notice that multiselect is enabled because of the word true.
Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';
yourStr = yourStr.slice(0, -4); // 'test'
Since you are using jQuery, how about using a trigger-reset:
$(document).ready(function(){
$('#shares').trigger(':reset');
});
If you want to UPSERT more than one record at a time you can use the ANSI SQL:2003 DML statement MERGE.
MERGE INTO table_name WITH (HOLDLOCK) USING table_name ON (condition)
WHEN MATCHED THEN UPDATE SET column1 = value1 [, column2 = value2 ...]
WHEN NOT MATCHED THEN INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...])
Check out Mimicking MERGE Statement in SQL Server 2005.
Filestash is the perfect tool for that:
Also Filestash is open source. (Disclaimer: I am the author)
you can also hide the gridline on yAxis as:
yAxis:{
gridLineWidth: 0,
minorGridLineWidth: 0
}
Start with the use of tabs - the \t character modifier. It will advance to a fixed location (columns, terminal lingo).
However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).
To fix that, write your "OK/NOK" stuff using a fixed number of tabs (5? 6?, try it). Then return (\r) without new-lining, and write your message.
found it on this site, it works on me. Modify /res/values/styles.xml from:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
to:
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
</style>
For me a DNS name of my server was added to /etc/hosts and it was mapped to 127.0.0.1 which resulted in
SL23_GET_SERVER_HELLO:unknown protocol
Removing mapping of my real DNS name to 127.0.0.1 resolved the problem.
Create a "jump link" using the following format:
http://www.somesite.com/somepage#anchor
Where anchor is the id of the element you wish to link to on that page. Use browser development tools / view source to find the id of the element you wish to link to.
If the element doesnt have an id and you dont control that site then you cant do it.
You can't have ngFor
and ngIf
on the same element. What you could do is hold off on populating the array you're using in ngFor
until the toggle in your example is clicked.
Here's a basic (not great) way you could do it: http://plnkr.co/edit/Pylx5HSWIZ7ahoC7wT6P
you can use following code.
file_obj = open('big_file')
open() returns a file object
then use os.stat for getting size
file_size = os.stat('big_file').st_size
for i in range( file_size/1024):
print file_obj.read(1024)
I think that if you put a span style after the <a>
tag with text-decoration:none
it will work in the majority of the browsers / email clients.
As in:
<a href="" style="text-decoration:underline">
<span style="color:#0b92ce; text-decoration:none">BANANA</span>
</a>
For Bootstrap 3 the default radio/button-group structure is :
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="radio" name="options" id="option1"> Option 1
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2"> Option 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3"> Option 3
</label>
</div>
And you can select the active one like this:
$('.btn-primary').on('click', function(){
alert($(this).find('input').attr('id'));
});
Check out my answer: https://stackoverflow.com/a/60201016/12529885
Try to specific the argument -sysdir
manually, and check whether the error message changed.
They may not a clearly hit, see the source code https://android.googlesource.com/platform/external/qemu/+/1a15692cded92d66dea1a51389a3c4b9e3b3631a/android/emulator/main-emulator.cpp
And you may solve it easily than searching online.
if (!strcmp(opt, "-sysdir") && nn+1 < argc) {
sysDir = argv[nn+1];
continue;
}
// some other codes.....
if (avdName) {
if (!isCpuArchSupportedByRanchu(avdArch)) {
APANIC("CPU Architecture '%s' is not supported by the QEMU2 emulator, (the classic engine is deprecated!)",
avdArch);
}
std::string systemPath = getAvdSystemPath(avdName, sysDir);
if (systemPath.empty()) {
const char* env = getenv("ANDROID_SDK_ROOT");
if (!env || !env[0]) {
APANIC("Cannot find AVD system path. Please define "
"ANDROID_SDK_ROOT\n");
} else {
APANIC("Broken AVD system path. Check your ANDROID_SDK_ROOT "
"value [%s]!\n",
env);
}
}
}
I've gotten the following to work:
html {
background:
linear-gradient(rgba(0,184,255,0.45),rgba(0,184,255,0.45)),
url('bgimage.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
The above will produce a nice opaque blue overlay.
I would typically do something like this (onblur), but it could be attached to any of the events:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function CheckNo(sender){
if(!isNaN(sender.value)){
if(sender.value > 100 )
sender.value = 100;
if(sender.value < 0 )
sender.value = 0;
}else{
sender.value = 0;
}
}
</script>
</head>
<body>
<input type="text" onblur="CheckNo(this)" />
</body>
</html>
primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}
I simplified the test a bit - if all(x%y
instead of if not any(not x%y
I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.
pairs = {(x, x+2) for x in primes if x+2 in primes}
Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.
As Hogan notes above, use an AND
instead of &
. See this tutorial for more info.
__all__
customizes *
in from <module> import *
__all__
customizes *
in from <package> import *
A module is a .py
file meant to be imported.
A package is a directory with a __init__.py
file. A package usually contains modules.
""" cheese.py - an example module """
__all__ = ['swiss', 'cheddar']
swiss = 4.99
cheddar = 3.99
gouda = 10.99
__all__
lets humans know the "public" features of a module.[@AaronHall] Also, pydoc recognizes them.[@Longpoke]
See how swiss
and cheddar
are brought into the local namespace, but not gouda
:
>>> from cheese import *
>>> swiss, cheddar
(4.99, 3.99)
>>> gouda
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'gouda' is not defined
Without __all__
, any symbol (that doesn't start with an underscore) would have been available.
*
are not affected by __all__
>>> import cheese
>>> cheese.swiss, cheese.cheddar, cheese.gouda
(4.99, 3.99, 10.99)
>>> from cheese import swiss, cheddar, gouda
>>> swiss, cheddar, gouda
(4.99, 3.99, 10.99)
>>> import cheese as ch
>>> ch.swiss, ch.cheddar, ch.gouda
(4.99, 3.99, 10.99)
In the __init__.py
file of a package __all__
is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__
customizes the *
when wildcard-importing from the package.[@MartinStettner]
Here's an excerpt from the Python MySQL Connector __init__.py
:
__all__ = [
'MySQLConnection', 'Connect', 'custom_error_exception',
# Some useful constants
'FieldType', 'FieldFlag', 'ClientFlag', 'CharacterSet', 'RefreshOption',
'HAVE_CEXT',
# Error handling
'Error', 'Warning',
...etc...
]
The default case, asterisk with no __all__
for a package, is complicated, because the obvious behavior would be expensive: to use the file system to search for all modules in the package. Instead, in my reading of the docs, only the objects defined in __init__.py
are imported:
If
__all__
is not defined, the statementfrom sound.effects import *
does not import all submodules from the packagesound.effects
into the current namespace; it only ensures that the packagesound.effects
has been imported (possibly running any initialization code in__init__.py
) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by__init__.py
. It also includes any submodules of the package that were explicitly loaded by previous import statements.
And lastly, a venerated tradition for stack overflow answers, professors, and mansplainers everywhere, is the bon mot of reproach for asking a question in the first place:
Wildcard imports ... should be avoided, as they [confuse] readers and many automated tools.
[PEP 8, @ToolmakerSteve]
This may be helpful :
SecureRandom.base64(15).tr('+/=', '0aZ')
If you want to remove any special character than put in first argument '+/=' and any character put in second argument '0aZ' and 15 is the length here .
And if you want to remove the extra spaces and new line character than add the things like :
SecureRandom.base64(15).tr('+/=', '0aZ').strip.delete("\n")
Hope this will help to anybody.
Yes, there is a possibility of stack overflow. The C and C++ standard do not dictate things like stack depth, those are generally an environmental issue.
Most decent development environments and/or operating systems will let you tailor the stack size of a process, either at link or load time.
You should specify which OS and development environment you're using for more targeted assistance.
For example, under Ubuntu Karmic Koala, the default for gcc is 2M reserved and 4K committed but this can be changed when you link the program. Use the --stack
option of ld
to do that.
According to this excellent comparison made by GaspardP I would not choose this solution. It's not the worst, but it's not the best either. The only thing it got going for it is that it's possibly easier to understand.
I found the other two answers to be pretty hard to understand. They also produce some warnings in my compiler and the use of a find function in the decode part should result in a pretty bad efficiency. So I decided to roll my own.
Header:
#ifndef _BASE64_H_
#define _BASE64_H_
#include <vector>
#include <string>
typedef unsigned char BYTE;
class Base64
{
public:
static std::string encode(const std::vector<BYTE>& buf);
static std::string encode(const BYTE* buf, unsigned int bufLen);
static std::vector<BYTE> decode(std::string encoded_string);
};
#endif
Body:
static const BYTE from_base64[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 62, 255, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255,
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 63,
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255};
static const char to_base64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
std::string Base64::encode(const std::vector<BYTE>& buf)
{
if (buf.empty())
return ""; // Avoid dereferencing buf if it's empty
return encode(&buf[0], (unsigned int)buf.size());
}
std::string Base64::encode(const BYTE* buf, unsigned int bufLen)
{
// Calculate how many bytes that needs to be added to get a multiple of 3
size_t missing = 0;
size_t ret_size = bufLen;
while ((ret_size % 3) != 0)
{
++ret_size;
++missing;
}
// Expand the return string size to a multiple of 4
ret_size = 4*ret_size/3;
std::string ret;
ret.reserve(ret_size);
for (unsigned int i=0; i<ret_size/4; ++i)
{
// Read a group of three bytes (avoid buffer overrun by replacing with 0)
size_t index = i*3;
BYTE b3[3];
b3[0] = (index+0 < bufLen) ? buf[index+0] : 0;
b3[1] = (index+1 < bufLen) ? buf[index+1] : 0;
b3[2] = (index+2 < bufLen) ? buf[index+2] : 0;
// Transform into four base 64 characters
BYTE b4[4];
b4[0] = ((b3[0] & 0xfc) >> 2);
b4[1] = ((b3[0] & 0x03) << 4) + ((b3[1] & 0xf0) >> 4);
b4[2] = ((b3[1] & 0x0f) << 2) + ((b3[2] & 0xc0) >> 6);
b4[3] = ((b3[2] & 0x3f) << 0);
// Add the base 64 characters to the return value
ret.push_back(to_base64[b4[0]]);
ret.push_back(to_base64[b4[1]]);
ret.push_back(to_base64[b4[2]]);
ret.push_back(to_base64[b4[3]]);
}
// Replace data that is invalid (always as many as there are missing bytes)
for (size_t i=0; i<missing; ++i)
ret[ret_size - i - 1] = '=';
return ret;
}
std::vector<BYTE> Base64::decode(std::string encoded_string)
{
// Make sure string length is a multiple of 4
while ((encoded_string.size() % 4) != 0)
encoded_string.push_back('=');
size_t encoded_size = encoded_string.size();
std::vector<BYTE> ret;
ret.reserve(3*encoded_size/4);
for (size_t i=0; i<encoded_size; i += 4)
{
// Get values for each group of four base 64 characters
BYTE b4[4];
b4[0] = (encoded_string[i+0] <= 'z') ? from_base64[encoded_string[i+0]] : 0xff;
b4[1] = (encoded_string[i+1] <= 'z') ? from_base64[encoded_string[i+1]] : 0xff;
b4[2] = (encoded_string[i+2] <= 'z') ? from_base64[encoded_string[i+2]] : 0xff;
b4[3] = (encoded_string[i+3] <= 'z') ? from_base64[encoded_string[i+3]] : 0xff;
// Transform into a group of three bytes
BYTE b3[3];
b3[0] = ((b4[0] & 0x3f) << 2) + ((b4[1] & 0x30) >> 4);
b3[1] = ((b4[1] & 0x0f) << 4) + ((b4[2] & 0x3c) >> 2);
b3[2] = ((b4[2] & 0x03) << 6) + ((b4[3] & 0x3f) >> 0);
// Add the byte to the return value if it isn't part of an '=' character (indicated by 0xff)
if (b4[1] != 0xff) ret.push_back(b3[0]);
if (b4[2] != 0xff) ret.push_back(b3[1]);
if (b4[3] != 0xff) ret.push_back(b3[2]);
}
return ret;
}
Usage:
BYTE buf[] = "ABCD";
std::string encoded = Base64::encode(buf, 4);
// encoded = "QUJDRA=="
std::vector<BYTE> decoded = Base64::decode(encoded);
A bonus here is that the decode function can also decode the URL variant of Base64 encoding.
I faced this issue when we changed from one domain to another for API service.
Restarting the network router/modem fixed this issue.
Since ffmpeg transpose command is very slow, use the command below to rotate a video by 90 degrees clockwise.
Fast command (Without encoding)-
ffmpeg -i input.mp4 -c copy -metadata:s:v:0 rotate=270 output.mp4
For full video encoding (Slow command, does encoding)
ffmpeg -i inputFile -vf "transpose=1" -c:a copy outputFile
Do like this:
HTML
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
CSS
.parent{
width: 400px;
background: red;
}
.child{
float: left;
width:200px;
background:green;
height: 100px;
}
This is working jsfiddle. Change child width
to more then 200px
and they will stack.
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
You can also put the exclamation mark inside the brackets:
if [[ ! $PATH =~ $temp ]]
but you should anchor your pattern to reduce false positives:
temp=/mnt/silo/bin
pattern="(^|:)${temp}(:|$)"
if [[ ! "${PATH}" =~ ${pattern} ]]
which looks for a match at the beginning or end with a colon before or after it (or both). I recommend using lowercase or mixed case variable names as a habit to reduce the chance of name collisions with shell variables.
You also can set the width of a audio tag by JavaScript:
audio = document.getElementById('audio-id');
audio.style.width = '200px';
Exception object also contains original response e.response
, that could be useful if need to see error body in response from the server. For example:
try:
r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
r.raise_for_status()
except requests.exceptions.HTTPError as e:
print (e.response.text)
For pre 1.1 django it is simple (for default admin site instance):
reverse('admin_%s_%s_change' % (app_label, model_name), args=(object_id,))
As I understand the question, you want to mix some of a module's instance methods into a class.
Let's begin by considering how Module#include works. Suppose we have a module UsefulThings
that contains two instance methods:
module UsefulThings
def add1
self + 1
end
def add3
self + 3
end
end
UsefulThings.instance_methods
#=> [:add1, :add3]
and Fixnum
include
s that module:
class Fixnum
def add2
puts "cat"
end
def add3
puts "dog"
end
include UsefulThings
end
We see that:
Fixnum.instance_methods.select { |m| m.to_s.start_with? "add" }
#=> [:add2, :add3, :add1]
1.add1
2
1.add2
cat
1.add3
dog
Were you expecting UsefulThings#add3
to override Fixnum#add3
, so that 1.add3
would return 4
? Consider this:
Fixnum.ancestors
#=> [Fixnum, UsefulThings, Integer, Numeric, Comparable,
# Object, Kernel, BasicObject]
When the class include
s the module, the module becomes the class' superclass. So, because of how inheritance works, sending add3
to an instance of Fixnum
will cause Fixnum#add3
to be invoked, returning dog
.
Now let's add a method :add2
to UsefulThings
:
module UsefulThings
def add1
self + 1
end
def add2
self + 2
end
def add3
self + 3
end
end
We now wish Fixnum
to include
only the methods add1
and add3
. Is so doing, we expect to get the same results as above.
Suppose, as above, we execute:
class Fixnum
def add2
puts "cat"
end
def add3
puts "dog"
end
include UsefulThings
end
What is the result? The unwanted method :add2
is added to Fixnum
, :add1
is added and, for reasons I explained above, :add3
is not added. So all we have to do is undef
:add2
. We can do that with a simple helper method:
module Helpers
def self.include_some(mod, klass, *args)
klass.send(:include, mod)
(mod.instance_methods - args - klass.instance_methods).each do |m|
klass.send(:undef_method, m)
end
end
end
which we invoke like this:
class Fixnum
def add2
puts "cat"
end
def add3
puts "dog"
end
Helpers.include_some(UsefulThings, self, :add1, :add3)
end
Then:
Fixnum.instance_methods.select { |m| m.to_s.start_with? "add" }
#=> [:add2, :add3, :add1]
1.add1
2
1.add2
cat
1.add3
dog
which is the result we want.
Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).
json_encode($array,JSON_UNESCAPED_SLASHES);
You could do it like that:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
Do you want to only get JPEG files or all files?
In this case, it's probably because you are using the wrong brackets here:
document.getElementById['calendar'].src = loc;
should be
document.getElementById('calendar').src = loc;
-m1 is the last parent of the current branch that is being fixed, -m 2 is the original parent of the branch that got merged into this.
Tortoise Git can also help here if command line is confusing.
RStudio has a good free IDE that allows for Markdown and LaTeX.
Since C++ 11, you could do the following:
for(const auto& student : data)
{
std::cout << student.name << std::endl;
}
You can use "wildcards" with MATCH
so assuming "ASDFGHJK" in H1 as per Peter's reply you can use this regular formula
=INDEX(G:G,MATCH("*"&H1&"*",G:G,0)+3)
MATCH can only reference a single column or row so if you want to search 6 columns you either have to set up a formula with 6 MATCH functions or change to another approach - try this "array formula", assuming search data in A2:G100
=INDIRECT("R"&REPLACE(TEXT(MIN(IF(ISNUMBER(SEARCH(H1,A2:G100)),(ROW(A2:G100)+3)*1000+COLUMN(A2:G100))),"000000"),4,0,"C"),FALSE)
confirmed with Ctrl-Shift-Enter
In my case compared arrays contain only numbers and strings. This solution worked for me:
function are_arrs_equal(arr1, arr2){
return arr1.sort().toString() === arr2.sort().toString()
}
Let's test it!
arr1 = [1, 2, 3, 'nik']
arr2 = ['nik', 3, 1, 2]
arr3 = [1, 2, 5]
console.log (are_arrs_equal(arr1, arr2)) //true
console.log (are_arrs_equal(arr1, arr3)) //false
I have struggled mightily to get the behavior I want. This is the easiest and best way to get TypeScript files to compile on save, to the configuration I want, only THIS file (the saved file). It's a tasks.json and a keybindings.json.
public static List getUniqueValues(List input) {
return new ArrayList<>(new LinkedHashSet<>(incoming));
}
dont forget to implement your equals method first
It is possible to extend the relation with query functions:
<?php
public function comments()
{
return $this->hasMany('Comment')->orderBy('column');
}
[edit after comment]
<?php
class User
{
public function comments()
{
return $this->hasMany('Comment');
}
}
class Controller
{
public function index()
{
$column = Input::get('orderBy', 'defaultColumn');
$comments = User::find(1)->comments()->orderBy($column)->get();
// use $comments in the template
}
}
default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )
this will do it with just javascript - you can also put the function in a .js file and call it with onclick
//button
<div onclick="
document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>
I encountered the same problem, but I check find that I hadn't the parent table. So I just edit the parent migration in front of the child migration. Just do it.
http://www.refulz.com:8082/index.php#tab2?foo=789
Property Result
------------------------------------------
host www.refulz.com:8082
hostname www.refulz.com
port 8082
protocol http:
pathname index.php
href http://www.refulz.com:8082/index.php#tab2
hash #tab2
search ?foo=789
var x = $(location).attr('<property>');
This will work only if you have jQuery. For example:
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
$(location).attr('href'); // http://www.refulz.com:8082/index.php#tab2
$(location).attr('pathname'); // index.php
</script>
</html>
We couldn't assume perfectly valid input, and went with this variation of @Keith's answer:
public static TEnum ParseEnum<TEnum>(string value) where TEnum : struct
{
TEnum tmp;
if (!Enum.TryParse<TEnum>(value, true, out tmp))
{
tmp = new TEnum();
}
return tmp;
}
I think in Postgres you can play with formats for example if you want dd/mm/yyyy
TO_CHAR(submit_time, 'DD/MM/YYYY') as submit_date
I think the easiest way is creating a new XML file. In this case, let's call it "example.xml" in the drawable folder, and put in the follow code:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/blue"
android:state_pressed="true" />
</selector>
But before that you have to set the colors in the colors.xml file, in the values folder, like this:
<resources>
<color name="blue">#0000FF</color>
</resources>
That made, you just set the Button / ImageButton to use the new layout, like this:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/example"
/>
Then when you click that image, it will change to the color set in
<item android:drawable="@color/blue"
android:state_pressed="true" />
giving the feedback that you want...
FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
SET var=%%F
)
ECHO %var%
I always use the USEBACKQ so that if you have a string to insert or a long file name, you can use your double quotes without screwing up the command.
Now if your output will contain multiple lines, you can do this
SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
SET var!count!=%%F
SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ENDLOCAL
You can try this example class. and find icon content here: http://astronautweb.co/snippet/font-awesome/
#content h2:before {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
transform: translate(0, 0);
content: "\f007";
}
You can use Jinja's default
:
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
There is a way of doing this with tags, which allows for multiple defaults.
Assume you have the following struct, with 2 default tags default0 and default1.
type A struct {
I int `default0:"3" default1:"42"`
S string `default0:"Some String..." default1:"Some Other String..."`
}
Now it's possible to Set the defaults.
func main() {
ptr := &A{}
Set(ptr, "default0")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=3 ptr.S=Some String...
Set(ptr, "default1")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=42 ptr.S=Some Other String...
}
Here's the complete program in a playground.
If you're interested in a more complex example, say with slices and maps, then, take a look at creasty/defaultse
You need to add position:relative
to #wrap element.
When you add this, all child elements will be positioned in this element, not browser window.
If notepad is already started, you should write:
// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
//...
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
}
GetProcessesByName
returns an array of processes, so you should get the first one (or find the one you want).
If you want to start notepad
and send the key, you should write:
Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
The only situation in which the code may not work is when notepad
is started as Administrator and your application is not.
The best you can get with simple styles would be something like:
.likeabutton {
text-decoration: none; font: menu;
display: inline-block; padding: 2px 8px;
background: ButtonFace; color: ButtonText;
border-style: solid; border-width: 2px;
border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
}
.likeabutton:active {
border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
}
(Possibly with some kind of fix to stop IE6-IE7 treating focused buttons as being ‘active’.)
This won't necessarily look exactly like the buttons on the native desktop, though; indeed, for many desktop themes it won't be possible to reproduce the look of a button in simple CSS.
However, you can ask the browser to use native rendering, which is best of all:
.likeabutton {
appearance: button;
-moz-appearance: button;
-webkit-appearance: button;
text-decoration: none; font: menu; color: ButtonText;
display: inline-block; padding: 2px 8px;
}
Unfortunately, as you may have guessed from the browser-specific prefixes, this is a CSS3 feature that isn't suppoorted everywhere yet. In particular IE and Opera will ignore it. But if you include the other styles as backup, the browsers that do support appearance
drop that property, preferring the explicit backgrounds and borders!
What you might do is use the appearance
styles as above by default, and do JavaScript fixups as necessary, eg.:
<script type="text/javascript">
var r= document.documentElement;
if (!('appearance' in r || 'MozAppearance' in r || 'WebkitAppearance' in r)) {
// add styles for background and border colours
if (/* IE6 or IE7 */)
// add mousedown, mouseup handlers to push the button in, if you can be bothered
else
// add styles for 'active' button
}
</script>
In order to get the image view with the proper size and in the center, you should use the following approach:
let width = 120 // choose the image width
let height = 20 // choose the image height
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)) //44 is the standard size of the top bar
let imageView = UIImageView(frame: CGRect(x: (view.bounds.width - width)/2, y: (44 - height)/2, width: width, height: height))
imageView.contentMode = .scaleAspectFit //choose other if it makes sense
imageView.image = UIImage(named: "your_image_name")
titleView.addSubview(imageView)
navigationItem.titleView = titleView
If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.
path = 'C:\\Users\\Username\\Path\\To\\File'
with open(path, 'w') as f:
f.write(data)
Edit:
Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.
import os
cur_path = os.path.dirname(__file__)
new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
f.write(data)
Edit 2: One quick note about __file__
, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.
A good information: you don't need to check whether the Bundle object is null into the onCreate() method. Use the onRestoreInstanceState() method, which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null
Have you tried Build -> Rebuild project?
For security reasons, it is recommended to use sanitize
instead of html_safe
.
<%= sanitize @str %>
What's happening is that, as a security measure, Rails is escaping your string for you because it might have malicious code embedded in it. But if you tell Rails that your string is html_safe
, it'll pass it right through.
@str = "<b>Hi</b>".html_safe
<%= @str %>
OR
@str = "<b>Hi</b>"
<%= @str.html_safe %>
Using raw
works fine, but all it's doing is converting the string to a string, and then calling html_safe
. When I know I have a string, I prefer calling html_safe
directly, because it skips an unnecessary step and makes clearer what's going on. Details about string-escaping and XSS protection are in this Asciicast.
You can find your database file :
Context.getDatabasePath(getDatabaseName())
getDatabaseName from class SQLiteOpenHelper
Use the longer version of IN which is a bunch of OR.
SELECT * FROM tablename
WHERE column LIKE 'M510%'
OR column LIKE 'M615%'
OR column LIKE 'M515%'
OR column LIKE 'M612%';
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:actionBarStyle">@style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:background">#C1000E</item>
<item name="android:titleTextStyle">@style/AppTheme.ActionBar.TitleTextStyle</item>
</style>
<style name="AppTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.StatusBar.Title">
<item name="android:textColor">#E5ED0E</item>
</style>
I have Solved Using That.
It is Work for me:
language:{"infoEmpty": "No records available",}
I used:
pip install Pillow
and pip installed PIL in Lib\site-packages. When I moved PIL to Lib everything worked fine. I'm on Windows 10.
Here's one way...
>>> s = '2134'
>>> def swap(c, i, j):
... c = list(c)
... c[i], c[j] = c[j], c[i]
... return ''.join(c)
...
>>> swap(s, 0, 1)
'1234'
>>>
Try using
<table border="1" cellspacing="0" cellpadding="0" class="template-table"
style="table-layout: fixed; width: 100%">
as table style along with
<td style="word-break:break-word">long text</td>
for td it works for normal/real scenario text with words, not for random typed letters without gaps
add a new .css class:
#test.nohover:hover { border: 0 }
and
<div id="test" class="nohover">blah</div>
The more "specific" css rule wins, so this border:0 version will override the generic one specified elsewhere.
I think there was some bugs in previous App-Compat lib for child Fragment. I tried @Vidar Wahlberg and @Matt's ans they did not work for me. After updating the appcompat library my code run perfectly without any extra effort.
docs: SQL Expression Language Tutorial - Using Text
example:
from sqlalchemy.sql import text
connection = engine.connect()
# recommended
cmd = 'select * from Employees where EmployeeGroup = :group'
employeeGroup = 'Staff'
employees = connection.execute(text(cmd), group = employeeGroup)
# or - wee more difficult to interpret the command
employeeGroup = 'Staff'
employees = connection.execute(
text('select * from Employees where EmployeeGroup = :group'),
group = employeeGroup)
# or - notice the requirement to quote 'Staff'
employees = connection.execute(
text("select * from Employees where EmployeeGroup = 'Staff'"))
for employee in employees: logger.debug(employee)
# output
(0, 'Tim', 'Gurra', 'Staff', '991-509-9284')
(1, 'Jim', 'Carey', 'Staff', '832-252-1910')
(2, 'Lee', 'Asher', 'Staff', '897-747-1564')
(3, 'Ben', 'Hayes', 'Staff', '584-255-2631')
This problem can be simply solved by closing Eclipse and restarting it. Eclipse sometimes fails to establish a connection with the Emulator, so this can happen in some cases.
I put this in my makefile, right the next line after adb install ...
adb shell monkey -p `cat .identifier` -c android.intent.category.LAUNCHER 1
For this to work there must be a .identifier file with the app's bundle identifier in it, like com.company.ourfirstapp
No need to hunt activity name.
If the file is small, you can read the whole data once:
File file = new File("a.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
String str = new String(data, "UTF-8");
First give the link of logout.php
page in that logout button.In that page make the code which is given below:
Here is the code:
<?php
session_start();
session_destroy();
?>
When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.
As Homebrew is my favorite for macOS although it is possible to have apt-get
on macOS using Fink.
to load a KeyStore, you'll need to tell it the type of keystore it is (probably jceks), provide an inputstream, and a password. then, you can load it like so:
KeyStore ks = KeyStore.getInstance(TYPE_OF_KEYSTORE);
ks.load(new FileInputStream(PATH_TO_KEYSTORE), PASSWORD);
this can throw a KeyStoreException, so you can surround in a try block if you like, or re-throw. Keep in mind a keystore can contain multiple keys, so you'll need to look up your key with an alias, here's an example with a symmetric key:
SecretKeyEntry entry = (KeyStore.SecretKeyEntry)ks.getEntry(SOME_ALIAS,new KeyStore.PasswordProtection(SOME_PASSWORD));
SecretKey someKey = entry.getSecretKey();
Some more explanations to the solution Rachel already gave:
"WPF Apps With The Model-View-ViewModel Design Pattern"
by Josh Smith
There is a simple why that I prefered to the bundle due to the no duplicate data in memory. It consists of a init public method for the fragment
private ArrayList<Music> listMusics = new ArrayList<Music>();
private ListView listMusic;
public static ListMusicFragment createInstance(List<Music> music) {
ListMusicFragment fragment = new ListMusicFragment();
fragment.init(music);
return fragment;
}
public void init(List<Music> music){
this.listMusic = music;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.musiclistview, container, false);
listMusic = (ListView) view.findViewById(R.id.musicListView);
listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));
return view;
}
}
In two words, you create an instance of the fragment an by the init method (u can call it as u want) you pass the reference of your list without create a copy by serialization to the instance of the fragment. This is very usefull because if you change something in the list u will get it in the other parts of the app and ofcourse, you use less memory.
If you just put '/' in the href it will reload the current window.
<a href="/">
Reload the page
</a>
_x000D_
The accepted answer by Jesper is correct but now outdated. The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.
Instead use the java.time framework, built into Java 8 and later, back-ported to Java 6 & 7 and further adapted to Android.
If you truly do not care about time-of-day and time zones, use LocalDate
in the java.time framework ().
LocalDate localDate = LocalDate.of( 2014 , 5 , 6 );
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If you want to use the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault()
. If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
LocalDate today = LocalDate.now( z ) ;
If you care about specific moments, specific points on the timeline, do not use LocalDate
. If you care about the date as seen through the wall-clock time used by the people of a certain region, do not use LocalDate
.
Be aware that if you have any chance of needing to deal with other time zones or UTC, this is the wrong way to go. Naïve programmers tend to think they do not need time zones when in fact they do.
Call toString
to generate a string in standard ISO 8601 format.
String output = localDate.toString();
2014-05-06
For other formats, search Stack Overflow for DateTimeFormatter
class.
Though now supplanted by java.time, you can use the similar LocalDate
class in the Joda-Time library (the inspiration for java.time).
LocalDate localDate = new LocalDate( 2014, 5, 6 );
Try webView.setBackgroundColor(Color.parseColor("#EDEDED"));
You have make div as server control using following code,
<div class="tab-pane active" id="portlet_tab1" runat="server">
then this div will be accessible in code behind.
Generally and simply it works like this:
<script>_x000D_
$(document).ready(function () {_x000D_
$('i').click(function () {_x000D_
$(this).toggleClass('fa-plus-square fa-minus-square');_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
This will work with every browser
div {
-khtml-opacity:.50;
-moz-opacity:.50;
-ms-filter:"alpha(opacity=50)";
filter:alpha(opacity=50);
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
opacity:.50;
}
If you don't want transparency to affect the entire container and its children, check this workaround. You must have an absolutely positioned child with a relatively positioned parent.
Check demo at http://www.impressivewebs.com/css-opacity-that-doesnt-affect-child-elements/
As Shafik already wrote you need to use the right format because scanf
gets you a char.
Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/
Hint: It's faster/nicer to write x=x+1
; the shorter way: x++;
Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.
this is a select command
FROM
user
WHERE
application_key = 'dsfdsfdjsfdsf'
AND email NOT LIKE '%applozic.com'
AND email NOT LIKE '%gmail.com'
AND email NOT LIKE '%kommunicate.io';
this update command
UPDATE user
SET email = null
WHERE application_key='dsfdsfdjsfdsf' and email not like '%applozic.com'
and email not like '%gmail.com' and email not like '%kommunicate.io';
Here's one application that works for me. In our case...I wanted the Sales team to use SVN for certain docs (Price sheets and such)...but a bit over there head.
I setup an Auto SVN like this: - Created a REPO in my SVN server. - Checked out repo into a DB folder call AutoSVN. - I run EasySVN on my PC, which auto commits and updates the REPO.
With he 'Auto', there are no log comments, but not critical for these particular docs.
The Sales guys use the DB folder...and simply maintain the file name of those docs that need version control such as price sheets.
I believe this excerpt from the Apache documentation, complements well the previous answers :
This directive is required when you use a relative path in a substitution in per-directory (htaccess) context unless either of the following conditions are true:
The original request, and the substitution, are underneath the DocumentRoot (as opposed to reachable by other means, such as Alias).
The filesystem path to the directory containing the RewriteRule, suffixed by the relative substitution is also valid as a URL path on the server (this is rare).
As previously mentioned, in other contexts, it is only useful to make your rule shorter. Moreover, also as previously mentioned, you can achieve the same thing by placing the htaccess file in the subdirectory.
tl;dr: JavaScript doesn't support associative arrays, therefore neither does JSON.
After all, it's JSON, not JSAAN. :)
So PHP has to convert your array into an object in order to encode into JSON.
For whatever reason the above would not work for me. This is what did:
if (tabControl.SelectedTab.Name == "tabName" )
{
.. do stuff
}
where tabControl.SelectedTab.Name is the name attribute assigned to the page in the tabcontrol itself.
Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.
I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.
EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/
This takes care of nulls
var body = JObject.Parse("anyjsonString");
body?.SelectToken("path-string-prop")?.ToString();
body?.SelectToken("path-double-prop")?.ToObject<double>();
EclipseLink to output the SQL(persistence.xml config):
<property name="eclipselink.logging.level.sql" value="FINE" />
use ROUND () (See examples ) function in sql server
select round(11.6,0)
result:
12.0
ex2:
select round(11.4,0)
result:
11.0
if you don't want the decimal part, you could do
select cast(round(11.6,0) as int)
I Just put CSS in my <div>
now working in code
position: relative; top: -22px;
No, but the 32-bit version runs just fine on 64-bit Windows.
You could also get the error if your Billing is not set up correctly.
Google hands out credit worth $300 or 12 months of free usage whichever runs out faster. After that you would need to enable billing.
Sometimes Web.config of the application ends up in an unconsistent state (duplicate declaration of http handlers, etc) To check which line in config is causing the error open IIS Manager and try to edit the handler mappings..it will display you the error line if there is such an error in web config.
Strangely such errors do not get logged in Event viewer or ULS
You can use all()
method instead of toArray()
method (see more: laravel documentation):
test::where('id' ,'>' ,0)->pluck('id')->all(); //returns array
If you need a string
, you can use without toArray()
attachment:
test::where('id' ,'>' ,0)->pluck('id'); //returns string
A VirtualHost would also work for this and may work better for you as you can host several projects without the need for subdirectories. Here's how you do it:
httpd.conf (or extra\httpd-vhosts.conf relative to httpd.conf. Trailing slashes "\" might cause it not to work):
NameVirtualHost *:80
# ...
<VirtualHost *:80>
DocumentRoot C:\projects\transitCalculator\trunk\
ServerName transitcalculator.localhost
<Directory C:\projects\transitCalculator\trunk\>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
HOSTS file (c:\windows\system32\drivers\etc\hosts usually):
# localhost entries
127.0.0.1 localhost transitcalculator.localhost
Now restart XAMPP and you should be able to access http://transitcalculator.localhost/ and it will map straight to that directory.
This can be helpful if you're trying to replicate a production environment where you're developing a site that will sit on the root of a domain name. You can, for example, point to files with absolute paths that will carry over to the server:
<img src="/images/logo.png" alt="My Logo" />
whereas in an environment using aliases or subdirectories, you'd need keep track of exactly where the "images" directory was relative to the current file.
I feel that one of the mentioned cons for "Handlebars" isnt' really valid anymore.
Handlebars.java now allows us to share the same template languages for both client and server which is a big win for large projects with 1000+ components that require serverside rendering for SEO
Take a look at https://github.com/jknack/handlebars.java
It's simple with open source 7zip SFX-Packager - easy way to just "Drag & drop" folders onto it, and it creates a portable/self-extracting package.
I used the jQuery slim version and got this error. By using the normal jQuery version the issue got resolved.
for(var key in object) {
console.log(object[key]);
}
Peter and Jesse are correct but just make sure you first select the mysql DB.
use mysql;
select User from mysql.user;
that should do your trick
15841:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:188:
...
SSL handshake has read 0 bytes and written 121 bytes
This is a handshake failure. The other side closes the connection without sending any data ("read 0 bytes"). It might be, that the other side does not speak SSL at all. But I've seen similar errors on broken SSL implementation, which do not understand newer SSL version. Try if you get a SSL connection by adding -ssl3
to the command line of s_client.
With the latest release of Bootstrap RC 3, changing the color of the icons is as simple as adding a class with the color you want and adding it to the span.
Default black color:
<h1>Password Changed <span class="glyphicon glyphicon-ok"></span></h1>
would become
<h1>Password Changed <span class="glyphicon glyphicon-ok icon-success"></span></h1>
CSS
.icon-success {
color: #5CB85C;
}
Use re.sub
directly, this allows you to specify a count
:
regex.sub('', url, 1)
(Note that the order of arguments is replacement
, original
not the opposite, as might be suspected.)
int
can't be null, but Integer
can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException
, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
The algorithm std::replace
works per element on a given sequence (so it replaces elements with different elements, and can not replace it with nothing). But there is no empty character. If you want to remove elements from a sequence, the following elements have to be moved, and std::replace
doesn't work like this.
You can try to use std::remove
(together with std::erase
) to achieve this.
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
I tried the following code and it worked for me.
<button class="btn btn-default center-block" type="submit">Button</button>
The button control is in a div and using center-block class of bootstrap helped me to align the button to the center of div
Check the link where you will find the center-block class
How about this solution
public class BaseActivity extends Activity
{
static String currentAct = "";
@Override
protected void onStart()
{
super.onStart();
if (currentAct.equals(""))
Toast.makeText(this, "Start", Toast.LENGTH_LONG).show();
currentAct = getLocalClassName();
}
@Override
protected void onStop()
{
super.onStop();
if (currentAct.equals(getLocalClassName()))
{
currentAct = "";
Toast.makeText(this, "Stop", Toast.LENGTH_LONG).show();
}
}
}
All Activity need to extends BaseActivity.
When an activity call another (A->B) then currentAct is not equal getLocalClassName() because the onStart() of the second activity (B) is called before the onStop() of the first (A) (https://developer.android.com/guide/components/activities.html#CoordinatingActivities).
When the user press the home button or change between application will just call onStop() and then currentAct is equal getLocalClassName().
Here is my version using Swift 5 and Core Graphics.
I have created a class to draw two circles. The first circle is created using addEllipse()
. It puts the ellipse into a square, thus creating a circle. I find it surprising that there is no function addCircle()
. The second circle is created using addArc()
of 2pi radians
import UIKit
@IBDesignable
class DrawCircles: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
print("could not get graphics context")
return
}
context.setLineWidth(2)
context.setStrokeColor(UIColor.blue.cgColor)
context.addEllipse(in: CGRect(x: 30, y: 30, width: 50.0, height: 50.0))
context.strokePath()
context.setStrokeColor(UIColor.red.cgColor)
context.beginPath() // this prevents a straight line being drawn from the current point to the arc
context.addArc(center: CGPoint(x:100, y: 100), radius: 20, startAngle: 0, endAngle: 2.0*CGFloat.pi, clockwise: false)
context.strokePath()
}
}
in your ViewController's didViewLoad()
add the following:
let myView = DrawCircles(frame: CGRect(x: 50, y: 50, width: 300, height: 300))
self.view.addSubview(myView)
When it runs it should look like this. I hope you like my solution!
Applying a selector from the .nav-tabs
seems to be working:
See this demo.
$(document).ready(function(){
activaTab('aaa');
});
function activaTab(tab){
$('.nav-tabs a[href="#' + tab + '"]').tab('show');
};
I would prefer @codedme's answer, since if you know which tab you want prior to page load, you should probably change the page html and not use JS for this particular task.
I tweaked the demo for his answer, as well.
(If this is not working for you, please specify your setting - browser, environment, etc.)
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
I know this post is old but it was the first one that popped up when I did a search. I tried @Kim Kling RegExp but it failed miserably. Also prior to finding this forum I had tried almost all the other variations listed here. In the end, none of them worked except this one I created; it works fine, plus it is es6:
const regex = new RegExp(/[^0-9]/, 'g');
const val = document.forms["myForm"]["age"].value;
if (val.match(regex)) {
alert("Must be a valid number");
}
It's actually Document Object Model. HTML is used to build the DOM which is an in-memory representation of the page (while closely related to HTML, they are not exactly the same thing). Things like CSS and Javascript interact with the DOM.
HTML5 ARIA attribute is what you're looking for. It can be used in your code even without bootstrap.
Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications (especially those developed with Ajax and JavaScript) more accessible to people with disabilities.
To be precise for your question, here is what your attributes are called as ARIA attribute states and model
aria-labelledby
: Identifies the element (or elements) that labels the current element.
aria-hidden (state)
: Indicates that the element and all of its descendants are not visible or perceivable to any user as implemented by the author.
Java has static methods that are associated with classes (e.g. java.lang.Math has only static methods), but the class itself is not static.
var minRows = 5;
var maxRows = 26;
function ResizeTextarea(id) {
var t = document.getElementById(id);
if (t.scrollTop == 0) t.scrollTop=1;
while (t.scrollTop == 0) {
if (t.rows > minRows)
t.rows--; else
break;
t.scrollTop = 1;
if (t.rows < maxRows)
t.style.overflowY = "hidden";
if (t.scrollTop > 0) {
t.rows++;
break;
}
}
while(t.scrollTop > 0) {
if (t.rows < maxRows) {
t.rows++;
if (t.scrollTop == 0) t.scrollTop=1;
} else {
t.style.overflowY = "auto";
break;
}
}
}
I had different version of annotations jar. Changed all 3 jars to use SAME version of databind,annotations and core jackson jars
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.6</version>
</dependency>
Check if the Data
directory is in "C:\ProgramData\MySQL\MySQL Server 5.7\Data"
. This is where it is on my computer. Someone might find this helpful.
Try:
awk -F',' '{print $3}' myfile.txt
Here in -F you are saying to awk that use "," as field separator.
but.onclick = function() { yourjavascriptfunction();};
or
but.onclick = function() { functionwithparam(param);};
As the error message says, you have an inline style, which CSP prohibits. I see at least one (list-style: none
) in your HTML. Put that style in your CSS file instead.
To explain further, Content Security Policy does not allow inline CSS because it could be dangerous. From An Introduction to Content Security Policy:
"If an attacker can inject a script tag that directly contains some malicious payload .. the browser has no mechanism by which to distinguish it from a legitimate inline script tag. CSP solves this problem by banning inline script entirely: it’s the only way to be sure."
Here's another way of listing files inside a directory (using a different tool, not as efficient as some of the other answers).
cd "search_dir"
for [ z in `echo *` ]; do
echo "$z"
done
echo *
Outputs all files of the current directory. The for
loop iterates over each file name and prints to stdout.
Additionally, If looking for directories inside the directory then place this inside the for
loop:
if [ test -d $z ]; then
echo "$z is a directory"
fi
test -d
checks if the file is a directory.
All previous answers are great , i just thought to give an insight on why a structure can't contain an instance of its own type (not a reference).
its very important to note that structures are 'value' types i.e they contain the actual value, so when you declare a structure the compiler has to decide how much memory to allocate to an instance of it, so it goes through all its members and adds up their memory to figure out the over all memory of the struct, but if the compiler found an instance of the same struct inside then this is a paradox (i.e in order to know how much memory struct A takes you have to decide how much memory struct A takes !).
But reference types are different, if a struct 'A' contains a 'reference' to an instance of its own type, although we don't know yet how much memory is allocated to it, we know how much memory is allocated to a memory address (i.e the reference).
HTH
The timestamp casted correctly between formats else there is a chance the fields would be misinterpreted.
Here is a working sample that is correct when two different dates (Date2, Date1) are considered from table TableXYZ.
SELECT ROUND (totalSeconds / (24 * 60 * 60), 1) TotalTimeSpendIn_DAYS,
ROUND (totalSeconds / (60 * 60), 0) TotalTimeSpendIn_HOURS,
ROUND (totalSeconds / 60) TotalTimeSpendIn_MINUTES,
ROUND (totalSeconds) TotalTimeSpendIn_SECONDS
FROM (SELECT ROUND (
EXTRACT (DAY FROM timeDiff) * 24 * 60 * 60
+ EXTRACT (HOUR FROM timeDiff) * 60 * 60
+ EXTRACT (MINUTE FROM timeDiff) * 60
+ EXTRACT (SECOND FROM timeDiff))
totalSeconds,
FROM (SELECT TO_TIMESTAMP (
TO_CHAR (Date2,
'yyyy-mm-dd HH24:mi:ss')
- 'yyyy-mm-dd HH24:mi:ss'),
TO_TIMESTAMP (
TO_CHAR (Date1,
'yyyy-mm-dd HH24:mi:ss'),
'yyyy-mm-dd HH24:mi:ss')
timeDiff
FROM TableXYZ))
Take a look at this article on Simple-talk.com by Pop Rivett. It walks you through creating a generic trigger that will log the OLDVALUE and the NEWVALUE for all updated columns. The code is very generic and you can apply it to any table you want to audit, also for any CRUD operation i.e. INSERT, UPDATE and DELETE. The only requirement is that your table to be audited should have a PRIMARY KEY (which most well designed tables should have anyway).
Here's the code relevant for your GUESTS Table.
IF NOT EXISTS
(SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Audit]')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE Audit
(Type CHAR(1),
TableName VARCHAR(128),
PK VARCHAR(1000),
FieldName VARCHAR(128),
OldValue VARCHAR(1000),
NewValue VARCHAR(1000),
UpdateDate datetime,
UserName VARCHAR(128))
GO
CREATE TRIGGER TR_GUESTS_AUDIT ON GUESTS FOR UPDATE
AS
DECLARE @bit INT ,
@field INT ,
@maxfield INT ,
@char INT ,
@fieldname VARCHAR(128) ,
@TableName VARCHAR(128) ,
@PKCols VARCHAR(1000) ,
@sql VARCHAR(2000),
@UpdateDate VARCHAR(21) ,
@UserName VARCHAR(128) ,
@Type CHAR(1) ,
@PKSelect VARCHAR(1000)
--You will need to change @TableName to match the table to be audited.
-- Here we made GUESTS for your example.
SELECT @TableName = 'GUESTS'
-- date and user
SELECT @UserName = SYSTEM_USER ,
@UpdateDate = CONVERT (NVARCHAR(30),GETDATE(),126)
-- Action
IF EXISTS (SELECT * FROM inserted)
IF EXISTS (SELECT * FROM deleted)
SELECT @Type = 'U'
ELSE
SELECT @Type = 'I'
ELSE
SELECT @Type = 'D'
-- get list of columns
SELECT * INTO #ins FROM inserted
SELECT * INTO #del FROM deleted
-- Get primary key columns for full outer join
SELECT @PKCols = COALESCE(@PKCols + ' and', ' on')
+ ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
-- Get primary key select for insert
SELECT @PKSelect = COALESCE(@PKSelect+'+','')
+ '''<' + COLUMN_NAME
+ '=''+convert(varchar(100),
coalesce(i.' + COLUMN_NAME +',d.' + COLUMN_NAME + '))+''>'''
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
IF @PKCols IS NULL
BEGIN
RAISERROR('no PK on table %s', 16, -1, @TableName)
RETURN
END
SELECT @field = 0,
@maxfield = MAX(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName
WHILE @field < @maxfield
BEGIN
SELECT @field = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND ORDINAL_POSITION > @field
SELECT @bit = (@field - 1 )% 8 + 1
SELECT @bit = POWER(2,@bit - 1)
SELECT @char = ((@field - 1) / 8) + 1
IF SUBSTRING(COLUMNS_UPDATED(),@char, 1) & @bit > 0
OR @Type IN ('I','D')
BEGIN
SELECT @fieldname = COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND ORDINAL_POSITION = @field
SELECT @sql = '
insert Audit ( Type,
TableName,
PK,
FieldName,
OldValue,
NewValue,
UpdateDate,
UserName)
select ''' + @Type + ''','''
+ @TableName + ''',' + @PKSelect
+ ',''' + @fieldname + ''''
+ ',convert(varchar(1000),d.' + @fieldname + ')'
+ ',convert(varchar(1000),i.' + @fieldname + ')'
+ ',''' + @UpdateDate + ''''
+ ',''' + @UserName + ''''
+ ' from #ins i full outer join #del d'
+ @PKCols
+ ' where i.' + @fieldname + ' <> d.' + @fieldname
+ ' or (i.' + @fieldname + ' is null and d.'
+ @fieldname
+ ' is not null)'
+ ' or (i.' + @fieldname + ' is not null and d.'
+ @fieldname
+ ' is null)'
EXEC (@sql)
END
END
GO
on command line
example$:python
>>> import scipy
>>> scipy.__version__
'0.9.0'
It depends on many things. It's usually O(1), with a decent hash which itself is constant time... but you could have a hash which takes a long time to compute, and if there are multiple items in the hash map which return the same hash code, get
will have to iterate over them calling equals
on each of them to find a match.
In the worst case, a HashMap
has an O(n) lookup due to walking through all entries in the same hash bucket (e.g. if they all have the same hash code). Fortunately, that worst case scenario doesn't come up very often in real life, in my experience. So no, O(1) certainly isn't guaranteed - but it's usually what you should assume when considering which algorithms and data structures to use.
In JDK 8, HashMap
has been tweaked so that if keys can be compared for ordering, then any densely-populated bucket is implemented as a tree, so that even if there are lots of entries with the same hash code, the complexity is O(log n). That can cause issues if you have a key type where equality and ordering are different, of course.
And yes, if you don't have enough memory for the hash map, you'll be in trouble... but that's going to be true whatever data structure you use.
by VB function:
Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue
If Not m_RowNr(1) = strQName Then
m_RowNr(0) = 1
m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
m_RowNr(0) = m_RowNr(0) + 1
End If
m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)
End Function
Usage(without sorting option):
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id
if sorting required or multiple tables join then create intermediate table:
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
INTO table_with_Nr
From table A
Order By A.id