HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
This website has some nice examples for using spring's RestTemplate. Here is a code example of how it can work to get a simple object:
private static void getEmployees()
{
final String uri = "http://localhost:8080/springrestexample/employees.xml";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);
System.out.println(result);
}
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
def get_code(str)
str.sub(/^(Z_.*): .*/, '\1')
end
get_code('Z_foo: bar!') # => "Z_foo"
jquery ui has a great datepicker you can find it here
http://jqueryui.com/demos/datepicker/
you can use
http://jqueryui.com/demos/datepicker/#event-onSelect
to make your own actions when a date is picked
and if you want it to open without a form you could create a form that's hidden and then bind a click event to it like this
$("button").click(function() {
$(inputselector).datepicker('show');
});
When I encountered a similar problem, I fixed it by substituting &mode=xml
for &mode=json
in the request.
There is no linguistic support to do what you're asking for.
You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields()
to get an array of Field
), but depending on what you're trying to do, this may not be the best solution.
Here's a simple example to show only some of what reflection is capable of doing.
import java.lang.reflect.*;
public class DumpFields {
public static void main(String[] args) {
inspect(String.class);
}
static <T> void inspect(Class<T> klazz) {
Field[] fields = klazz.getDeclaredFields();
System.out.printf("%d fields:%n", fields.length);
for (Field field : fields) {
System.out.printf("%s %s %s%n",
Modifier.toString(field.getModifiers()),
field.getType().getSimpleName(),
field.getName()
);
}
}
}
The above snippet uses reflection to inspect all the declared fields of class String
; it produces the following output:
7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER
These are excerpts from the book:
Given a
Class
object, you can obtainConstructor
,Method
, andField
instances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:
- You lose all the benefits of compile-time checking.
- The code required to perform reflective access is clumsy and verbose.
- Performance suffers.
As a rule, objects should not be accessed reflectively in normal applications at runtime.
There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.
I use this:
@var.respond_to?(:keys)
It works for Hash and ActiveSupport::HashWithIndifferentAccess.
The practical reason why this doesn't work is not related to threads. The point is that node.left
is effectively translated into node.getLeft()
.
This property getter might be defined as:
val left get() = if (Math.random() < 0.5) null else leftPtr
Therefore two calls might not return the same result.
This casing can also be called a "slug", and the process of turning a phrase into it "slugify".
Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r
: r"Hello\tWorld\nHello World"
.
>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World
Also, \s
is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.
For Unix Users
find ~/.m2 -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \;
Right-click your project and choose Update Dependencies
For Windows
for /r %i in (*.lastUpdated) do del %i
This is a sample spark code which can read the files present on s3
val hadoopConf = sparkContext.hadoopConfiguration
hadoopConf.set("fs.s3.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
hadoopConf.set("fs.s3.awsAccessKeyId", s3Key)
hadoopConf.set("fs.s3.awsSecretAccessKey", s3Secret)
var jobInput = sparkContext.textFile("s3://" + s3_location)
If you have to wait there is a method presenceOfNestedElementLocatedBy
that takes the "parent" element and a locator, e.g. a By.xpath
:
WebElement subNode = new WebDriverWait(driver,10).until(
ExpectedConditions.presenceOfNestedElementLocatedBy(
divA, By.xpath(".//div/span")
)
);
What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.
null and undefined are both false for value equality (null==undefined): they both collapse to boolean false. They are not the same object (null!==undefined).
undefined is a property of the global object ("window" in browsers), but is a primitive type and not an object itself. It's the default value for uninitialized variables and functions ending without a return statement.
null is an instance of Object. null is used for DOM methods that return collection objects to indicate an empty result, which provides a false value without indicating an error.
To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:
Given the following function to test, located in module.a_function.to_test.py
:
from some_other.module import SomeOtherClass
def add_results():
my_object = SomeOtherClass('some_contextual_parameters')
result_a = my_object.method_a()
result_b = my_object.method_b()
return result_a + result_b
To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass
by using patch.object()
in combination with sys.modules
:
@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
mocked_other_class().method_a.return_value = 4
mocked_other_class().method_b.return_value = 7
self.assertEqual(add_results(), 11)
This works no matter the number of methods of SomeOtherClass
you need to patch, with independent results.
Also, using the same patching method, an actual instance of SomeOtherClass
can be returned if need be:
@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
other_class_instance = SomeOtherClass('some_controlled_parameters')
mocked_other_class.return_value = other_class_instance
...
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
I had similar situation as you and I ended up with using external library called arrow.
Here is what it looks like:
>>> import arrow
>>> enter = arrow.get('12:30:45', 'HH:mm:ss')
>>> exit = arrow.now()
>>> duration = exit - enter
>>> duration
datetime.timedelta(736225, 14377, 757451)
Here is a working css, tested under Firefox / IE7 / Safari / Chrome / Opera.
* {margin:0px;padding:0px;overflow:hidden}
div {position:absolute}
div#header {top:0px;left:0px;right:0px;height:60px}
div#wrapper {top:60px;left:0px;right:0px;bottom:0px;}
div#left {top:0px;bottom:0px;left:0px;width:50%;overflow-y:auto}
div#right {top:0px;bottom:0px;right:0px;width:50%;overflow-y:auto}
"overflow-y" is not w3c-approved, but every major browser supports it. Your two divs #left and #right will display a vertical scrollbar if their content is too high.
For this to work under IE7, you have to trigger the standards-compliant mode by adding a DOCTYPE :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"_x000D_
"http://www.w3.org/TR/html4/strict.dtd">_x000D_
<html>_x000D_
<head>_x000D_
<title></title>_x000D_
<style type="text/css">_x000D_
*{margin:0px;padding:0px;overflow:hidden}_x000D_
div{position:absolute}_x000D_
div#header{top:0px;left:0px;right:0px;height:60px}_x000D_
div#wrapper{top:60px;left:0px;right:0px;bottom:0px;}_x000D_
div#left{top:0px;bottom:0px;left:0px;width:50%;overflow-y:auto}_x000D_
div#right{top:0px;bottom:0px;right:0px;width:50%;overflow-y:auto}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div id="header"></div>_x000D_
<div id="wrapper">_x000D_
<div id="left"><div style="height:1000px">high content</div></div>_x000D_
<div id="right"></div>_x000D_
</div>_x000D_
</body>
_x000D_
You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).
By default, imshow
sets the aspect of the plot to 1, as this is often what people want for image data.
In your case, you can do something like:
import matplotlib.pyplot as plt
import numpy as np
grid = np.random.random((10,10))
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))
ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')
ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')
ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')
plt.tight_layout()
plt.show()
The answer of Anuja Patil only works with a single file input on a page. This works if there are more than one. This snippet will also show all files if multiple
is enabled.
<script type="text/javascript">
$('.custom-file input').change(function (e) {
var files = [];
for (var i = 0; i < $(this)[0].files.length; i++) {
files.push($(this)[0].files[i].name);
}
$(this).next('.custom-file-label').html(files.join(', '));
});
</script>
Note that $(this).next('.custom-file-label').html($(this)[0].files.join(', '));
does not work. So that is why the for
loop is needed.
If you never work with mulitple files in the file upload, this simpler snippet can be used.
<script type="text/javascript">
$('.custom-file input').change(function (e) {
if (e.target.files.length) {
$(this).next('.custom-file-label').html(e.target.files[0].name);
}
});
</script>
Similar to what Muhammad Iqbal stated.. I was in a VB.NET (may also be C#) project where I did remove a key-value pair from the App.config
which was referenced by a variable global to the Sub Main()
of Module Main
. Therefore, the exception (and break) occurs in Module Main
before the Sub Main()
. If only I had a break-point on the Dim
, but we don't usually break on global variables. Perhaps a good reason not to declare globals referencing App.config? In other words, this...
An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module. The type initializer for 'Namespace.Main' threw an exception.
Is caused by...
App.config
<connectionStrings>
<!--<add name="ConnectionString1" connectionString="..." />-->
Main module
Module Main
Dim cnnString As String = ConfigurationManager.ConnectionStrings("ConnectionString1") '<-- BREAK HERE (EXCEPTION)
Sub Main()
// main code
End Main
End Module
Since Git 2.7.0 Git will take exceptions into account. From the official release notes:
- Allow a later "!/abc/def" to override an earlier "/abc" that appears in the same .gitignore file to make it easier to express "everything in /abc directory is ignored, except for ...".
https://raw.githubusercontent.com/git/git/master/Documentation/RelNotes/2.7.0.txt
edit: apparently this doesn't work any more since Git 2.8.0
If you are using NumPy (as in ludaavic's answer), for large arrays you'll probably want to use NumPy's sum
function rather than Python's builtin sum
for a significant speedup -- e.g., a >1000x speedup for 10 million element arrays on my laptop:
>>> import numpy as np
>>> ten_million = 10 * 1000 * 1000
>>> x, y = (np.random.randn(ten_million) for _ in range(2))
>>> %timeit sum(x > y) # time Python builtin sum function
1 loops, best of 3: 24.3 s per loop
>>> %timeit (x > y).sum() # wow, that was really slow! time NumPy sum method
10 loops, best of 3: 18.7 ms per loop
>>> %timeit np.sum(x > y) # time NumPy sum function
10 loops, best of 3: 18.8 ms per loop
(above uses IPython's %timeit
"magic" for timing)
/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
g.setColor(Color.RED);
g.fillOval(50,50,20,20);
}
g.fillOval(x-axis,y-axis,width,height);
I have implemented Alert Dialog for exception throwing on to the current activitty view.Whenever I had given like this
AlertDialog.Builder builder = new AlertDialog.Builder(context);
Given same Window Exception.I write code for alert out of onCreate().So simple I used context = this;
after setContentView()
statement in onCreate()
method.Taken context variable as global like Context context;
Code sample is
static Context context;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.network);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
context = this;
.......
Alert Method Sample is
private void alertException(String execMsg){
Log.i(TAG,"in alertException()..."+context);
Log.e(TAG,"Exception :"+execMsg);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
.......
It works fine for me.Actually I searched for this error on StackOverflow I found this query.After reading all responses of this post, I tried this way so It works .I thought this is a simple solution for overcome the exception.
Thanks, Rajendar
You can't call free
on the pointers returned from strsep
. Those are not individually allocated strings, but just pointers into the string s
that you've already allocated. When you're done with s
altogether, you should free it, but you do not have to do that with the return values of strsep
.
I added it for all fieldsets with
fieldset {
border: 1px solid lightgray;
}
I didnt work if I set it separately using for example
border-color : red
. Then a black line was drawn next to the red line.
I came across this when I wanted to make the axis labels smaller, but leave everything else the same size. The command that worked for me, was to put:
par(cex.axis=0.5)
Before the plot command. Just remember to put:
par(cex.axis=1.0)
After the plot to make sure that the fonts go back to the default size.
This is a reported webkit (chrome/safari) bug, children of parents with min-height can't inherit the height property: https://bugs.webkit.org/show_bug.cgi?id=26559
Apparently Firefox is affected too (can't test in IE at the moment)
Possible workaround:
The bug doesn't show when the inner element has absolute positioning.
See http://jsfiddle.net/xrebB/
Edit on April 10, 2014
Since I'm currently working on a project for which I really need parent containers with min-height
, and child elements inheriting the height of the container, I did some more research.
First: I'm not so sure anymore whether the current browser behaviour really is a bug. CSS2.1 specs say:
The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.
If I put a min-height on my container, I'm not explicitly specifying its height - so my element should get an auto
height. And that's exactly what Webkit - and all other browsers - do.
Second, the workaround I found:
If I set my container element to display:table
with height:inherit
it acts exactly the same way as if I'd give it a min-height
of 100%. And - more importantly - if I set the child element to display:table-cell
it will perfectly inherit the height of the container element - whether it's 100% or more.
Full CSS:
html, body {
height: 100%;
margin: 0;
}
#container {
background: green;
display: table;
height: inherit;
width: 100%;
}
#content {
background: red;
display: table-cell;
}
The markup:
<div id="container">
<div id="content">
<p>content</p>
</div>
</div>
It seems you don't even have to specify the compression any more. The following snippet loads the data from filename.zip into df.
import pandas as pd
df = pd.read_csv('filename.zip')
(Of course you will need to specify separator, header, etc. if they are different from the defaults.)
Use +, the string concatenation operator:
ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(""+x);
or use
String.valueOf(int):
ed.setText(String.valueOf(x));
or use
Integer.toString(int):
ed.setText(Integer.toString(x));
Expanding Gabi Purcaru's answer to include an answer to number 2.
a = new Array();
b = new Object();
a[0] = b;
var c = a[0]; // c is now the object we inserted into a...
I created a small hackMD to install cocoapods on MacOS 10.15 (Catalina) and 11 (Big Sur)
https://hackmd.io/@sBJPlhRESGqCKCqV8ZjP1A/S1UY3W7HP
Make sure you have xcode components are installed.
Download 'Command Line Tools' (about 500MB) directly from this link (Requires you to have apple account) https://developer.apple.com/downloads/index.action
Install the downloaded file
Click on Install
Install COCOAPODS files in terminal
sudo gem install -n /usr/local/bin cocoapods
int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);
imageView.setImageResource(id);
someLinearLayout.addView(imageView);
You could also get this error if you are viewing accessing the page locally (via file://
instead of http://
)..
There is some discussion about this here: https://github.com/jeromegn/Backbone.localStorage/issues/55
What we do, is to create two tables for each multilingual object.
E.g. the first table contains only language-neutral data (primary key, etc.) and the second table contains one record per language, containing the localized data plus the ISO code of the language.
In some cases we add a DefaultLanguage field, so that we can fall-back to that language if no localized data is available for a specified language.
Example:
Table "Product":
----------------
ID : int
<any other language-neutral fields>
Table "ProductTranslations"
---------------------------
ID : int (foreign key referencing the Product)
Language : varchar (e.g. "en-US", "de-CH")
IsDefault : bit
ProductDescription : nvarchar
<any other localized data>
With this approach, you can handle as many languages as needed (without having to add additional fields for each new language).
Update (2014-12-14): please have a look at this answer, for some additional information about the implementation used to load multilingual data into an application.
In my case it happened when calling a function by passing a parameter of a Core Data managed object's property. At the time of calling the object was no longer existed, and that caused this error.
I have solved the issue by checking if the managed object exists or not before calling the function.
The button code should be moved to the PlaceholderFragment()
class. There you will call the layout fragment_main.xml
in the onCreateView
method. Like so
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button) view.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
return view;
}
It will also work if you call intern()
on the string before inserting it into the array.
Interned strings are reference-equal (==
) if and only if they are value-equal (equals()
.)
public static void main (String... aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos="Jorman 14988611";
StringTokenizer tokens=new StringTokenizer(strDatos, " ");
int nDatos=tokens.countTokens();
String[] datos=new String[nDatos];
int i=0;
while(tokens.hasMoreTokens()) {
String str=tokens.nextToken();
datos[i]= str.intern();
i++;
}
//System.out.println (usuario);
if(datos[0]==usuario) {
System.out.println ("WORKING");
}
We can specify how we have to join the string. Instead of '-', we can use ' '
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
file.write("This will be added to the next line\n")
or
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")
try http://code.google.com/p/swinghtmltemplate/
this will allow you to create gui with html-like syntax
drop table if exists foo;
create table foo
(
id int unsigned not null auto_increment primary key,
val smallint unsigned not null default 0
)
engine=innodb;
drop procedure if exists load_foo_test_data;
delimiter #
create procedure load_foo_test_data()
begin
declare v_max int unsigned default 1000;
declare v_counter int unsigned default 0;
truncate table foo;
start transaction;
while v_counter < v_max do
insert into foo (val) values ( floor(0 + (rand() * 65535)) );
set v_counter=v_counter+1;
end while;
commit;
end #
delimiter ;
call load_foo_test_data();
select * from foo order by id;
If it is a pandas data frame you could do:
csv_data.to_sql=(con=mydb, name='<the name of your table>',
if_exists='replace', flavor='mysql')
to avoid the use of the for
.
I use SingleOrDefault
in situations where my logic dictates that the will be either zero or one results. If there are more, it's an error situation, which is helpful.
Built a tiny, confirm-like vanilla js yes / no dialog.
https://www.npmjs.com/package/yesno-dialog
if file is committed and pushed to github then you should run
git rm --fileName
git ls-files
to make sure that the file is removed or untracked
git commit -m "UntrackChanges"
git push
You'd have to use WebSockets (or some similar protocol module e.g. as supported by the Flash plugin) because a normal browser application simply can't open a pure TCP socket.
The Socket.IO
module available for node.js
can help a lot, but note that it is not a pure WebSocket module in its own right.
It's actually a more generic communications module that can run on top of various other network protocols, including WebSockets, and Flash sockets.
Hence if you want to use Socket.IO
on the server end you must also use their client code and objects. You can't easily make raw WebSocket
connections to a socket.io
server as you'd have to emulate their message protocol.
Try this :
SELECT
(
SELECT
`NAME`
FROM
locations
WHERE
ID = school_locations.LOCATION_ID
) as `NAME`
FROM
school_locations
WHERE
(
SELECT
`TYPE`
FROM
locations
WHERE
ID = school_locations.LOCATION_ID
) = 'coun';
dict.iteritems() in python 2 is equivalent to dict.items() in python 3.
Code Snippet:
div{height: calc(100vh - 10vmax)}
An important reason is to add one and only one variable as the "Root" of your namespace...
var MyNamespace = {}
MyNamespace.foo= function() {
}
or
var MyNamespace = {
foo: function() {
},
...
}
There are many techniques for namespacing. It's become more important with the plethora of JavaScript modules available.
I'm not sure what you think this ORDER BY
is accomplishing? Even if you do put ORDER BY
in the view in a legal way (e.g. by adding a TOP
clause), if you just select from the view, e.g. SELECT * FROM dbo.TopUsersTest;
without an ORDER BY
clause, SQL Server is free to return the rows in the most efficient way, which won't necessarily match the order you expect. This is because ORDER BY
is overloaded, in that it tries to serve two purposes: to sort the results and to dictate which rows to include in TOP
. In this case, TOP
always wins (though depending on the index chosen to scan the data, you might observe that your order is working as expected - but this is just a coincidence).
In order to accomplish what you want, you need to add your ORDER BY
clause to the queries that pull data from the view, not to the code of the view itself.
So your view code should just be:
CREATE VIEW [dbo].[TopUsersTest]
AS
SELECT
u.[DisplayName], SUM(a.AnswerMark) AS Marks
FROM
dbo.Users_Questions AS uq
INNER JOIN [dbo].[Users] AS u
ON u.[UserID] = us.[UserID]
INNER JOIN [dbo].[Answers] AS a
ON a.[AnswerID] = uq.[AnswerID]
GROUP BY u.[DisplayName];
The ORDER BY
is meaningless so should not even be included.
To illustrate, using AdventureWorks2012, here is an example:
CREATE VIEW dbo.SillyView
AS
SELECT TOP 100 PERCENT
SalesOrderID, OrderDate, CustomerID , AccountNumber, TotalDue
FROM Sales.SalesOrderHeader
ORDER BY CustomerID;
GO
SELECT SalesOrderID, OrderDate, CustomerID, AccountNumber, TotalDue
FROM dbo.SillyView;
Results:
SalesOrderID OrderDate CustomerID AccountNumber TotalDue
------------ ---------- ---------- -------------- ----------
43659 2005-07-01 29825 10-4020-000676 23153.2339
43660 2005-07-01 29672 10-4020-000117 1457.3288
43661 2005-07-01 29734 10-4020-000442 36865.8012
43662 2005-07-01 29994 10-4020-000227 32474.9324
43663 2005-07-01 29565 10-4020-000510 472.3108
And you can see from the execution plan that the TOP
and ORDER BY
have been absolutely ignored and optimized away by SQL Server:
There is no TOP
operator at all, and no sort. SQL Server has optimized them away completely.
Now, if you change the view to say ORDER BY SalesID
, you will then just happen to get the ordering that the view states, but only - as mentioned before - by coincidence.
But if you change your outer query to perform the ORDER BY
you wanted:
SELECT SalesOrderID, OrderDate, CustomerID, AccountNumber, TotalDue
FROM dbo.SillyView
ORDER BY CustomerID;
You get the results ordered the way you want:
SalesOrderID OrderDate CustomerID AccountNumber TotalDue
------------ ---------- ---------- -------------- ----------
43793 2005-07-22 11000 10-4030-011000 3756.989
51522 2007-07-22 11000 10-4030-011000 2587.8769
57418 2007-11-04 11000 10-4030-011000 2770.2682
51493 2007-07-20 11001 10-4030-011001 2674.0227
43767 2005-07-18 11001 10-4030-011001 3729.364
And the plan still has optimized away the TOP
/ORDER BY
in the view, but a sort is added (at no small cost, mind you) to present the results ordered by CustomerID
:
So, moral of the story, do not put ORDER BY in views. Put ORDER BY in the queries that reference them. And if the sorting is expensive, you might consider adding/changing an index to support it.
From the information available on accessibility and the use of tooltips making them larger with the use of CR or line break is appreciated, the fact that the various browsers cannot/will not agree on basics shows that they don't much care about accessibility.
try ORDER BY MONTH(Date),DAY(DATE)
Try this:
ORDER BY YEAR(Date) DESC, MONTH(Date) DESC, DAY(DATE) DESC
Worked perfectly on a JET DB.
One-line numpy solution for downsampling (by 2):
smaller_img = bigger_img[::2, ::2]
And upsampling (by 2):
bigger_img = smaller_img.repeat(2, axis=0).repeat(2, axis=1)
(this asssumes HxWxC shaped image. h/t to L. Kärkkäinen in the comments above. note this method only allows whole integer resizing (e.g., 2x but not 1.5x))
Updates an old config with new/changed/removed options.
Not sure if I get you right, but the simplest way would be something like:
<c:if test="${languageBean.locale == 'en'">
<f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>
Just a quick copy and paste from an app of mine...
HTH
Not exactly. The h1.hc-reform > p
means "any p
exactly one level underneath h1.hc-reform
".
What you want is h1.hc-reform + p
. Of course, that might cause some issues in older versions of Internet Explorer; if you want to make the page compatible with older IEs, you'll be stuck with either adding a class manually to the paragraphs or using some JavaScript (in jQuery, for example, you could do something like $('h1.hc-reform').next('p').addClass('first-paragraph')
).
More info: http://www.w3.org/TR/CSS2/selector.html or http://css-tricks.com/child-and-sibling-selectors/
why dont you use export, then click 'Custom - display all possible options' radio button, then choose your database, then go to Output and choose 'View output as text' just scroll down and Go. Voila!
This will give you a sorted version of the array.
sorted(timestamps, reverse=True)
If you want to sort in-place:
timestamps.sort(reverse=True)
For everyone saying to get the bytes, copy it to MemoryStream
, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader
's built in ReadLine()
or ReadToEnd()
? I saw these weren't even mentioned, and they do everything for you.
I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult
that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:
string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";
string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine(); // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();
return path;
If you REALLY need a byte[]
instead of a string
for some reason, using my example, you can always do:
byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();
return toBytes;
(Returning toBytes
instead of path
.)
If you don't want ASCII
you can easily replace that with UTF8
, Unicode
, etc.
http://markusslima.github.io/bootstrap-filestyle/
$(":file").filestyle();
OR
<input type="file" class="filestyle" data-input="false">
I had enough success just catchig socket.timeout
and socket.error
; although socket.error can be raised for lots of reasons. Be careful.
import socket
import logging
hostname='google.com'
port=443
try:
sock = socket.create_connection((hostname, port), timeout=3)
except socket.timeout as err:
logging.error(err)
except socket.error as err:
logging.error(err)
import UIKit
class TabbarViewController: UITabBarController,UITabBarControllerDelegate {
//MARK:- View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//Tabbar delegate method
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
yourView.popToRootViewController(animated:false)
}
}
These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit
for Chrome, Safari; -moz
for Firefox, -o
for Opera, -ms
for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.
This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.
To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:
.elementClass {
-moz-border-radius: 2em;
-ms-border-radius: 2em;
-o-border-radius: 2em;
-webkit-border-radius: 2em;
border-radius: 2em;
}
Specifically, to address the CSS in your question, the lines you quote:
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;
Specify the column-count
, column-gap
and column-fill
properties for Webkit browsers and Firefox.
References:
<Button x:Name="myBtn_DetailsTab_Save" FlowDirection="LeftToRight" HorizontalAlignment="Left" Margin="835,544,0,0" VerticalAlignment="Top" Width="143" Height="53" BorderBrush="#FF0F6287" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" Click="myBtn_DetailsTab_Save_Click">
<StackPanel HorizontalAlignment="Stretch" Background="#FF1FB3F5" Cursor="Hand" >
<Image HorizontalAlignment="Left" Source="image/bg/Save.png" Height="36" Width="124" />
<TextBlock HorizontalAlignment="Center" Width="84" Height="22" VerticalAlignment="Top" Margin="0,-31,-58,0" Text="??? ?????" />
</StackPanel>
</Button>
You don't need "string" in your call to wordLengthFunction()
.
int wordLength = wordLengthFunction(string word);
should be
int wordLength = wordLengthFunction(word);
So I get you are using Eclipse with the M2E plugin. Try to update your Maven configuration : In the Project Explorer, right-click on the project, Maven -> Update project.
If the problem still remains, try to clean your project: right-click on your pom.xml, Run as -> Maven build (the second one). Enter "clean package" in the Goals fields. Check the Skip Tests box. Click on the Run button.
Edit: For your new problem, you need to add Spring MVC to your pom.xml. Add something like the following:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
Maybe you have to change the version to match the version of your Spring framework. Take a look here:
http://mvnrepository.com/artifact/org.springframework/spring-webmvc
For a shopping cart situation here's what I recommend. I'm gonna break it down into it's simplest form.
Assuming we start with this(a list view with 2 colums, 2 buttons, and a label):
First things first, removing the items, to do that we'll enter our remove button:
private void button2_Click(object sender, EventArgs e)
{
listView1.Items.Remove(listView1.SelectedItems[0]);
label1.Text = updateCartTotal().ToString();
}
Now the second line is updating our labels total using the next function i'll post to addup all the total of column 2 in the listview:
private decimal updateCartTotal()
{
decimal runningTotal = 0;
foreach(ListViewItem l in listView1.Items)
{
runningTotal += Convert.ToDecimal(l.SubItems[1].Text);
}
return runningTotal;
}
You don't have to use decimal like I did, you can use float or int if you don't have decimals. So let's break it down. We use a for loop to total all the items in the column 2(SubItems[1].Text). Add that to a decimal we declared prior to the foreach loop to keep a total. If you want to do tax you can do something like:
return runningTotal * 1.15;
or whatever your tax rate is.
Long and short of it, using this function you can retotal your listview by just calling the function. You can change the labels text like I demo'd prior if that's what you're after.
I guess inspect
is the best way to do this. For example:
import inspect
def bar():
print("My name is", inspect.stack()[0][3])
Just do:
echo substr($string, 0, -3);
You don't need to use a strlen
call, since, as noted in the substr docs:
If length is given and is negative, then that many characters will be omitted from the end of string
Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:
workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"
Only works if your file structure contains one instance of the text used to replace. YMMV.
One statement can be written as such:
someValues.forEach(x => console.log(x));
or multiple statements can be enclosed in {}
like this:
someValues.forEach(x => { let a = 2 + x; console.log(a); });
public static Bitmap RotateBitmap(Bitmap source, float angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
To get Bitmap from resources:
Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);
Looks like this exception message is quite generic and can be received due to a variety of reasons. We ran into this while deploying the client on Windows 8.1 machines. Our WCF client runs inside of a windows service and continuously polls the WCF service. The windows service runs under a non-admin user. The issue was fixed by setting the clientCredentialType to "Windows" in the WCF configuration to allow the authentication to pass-through, as in the following:
<security mode="None">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
I'm having this problem myself - my page breaks work in every browser but Chrome - and was able to isolate it down to the page-break-after element being inside a table cell. (Old, inherited templates in the CMS.)
Apparently Chrome doesn't honor the page-break-before or page-break-after properties inside table cells, so this modified version of Phil's example puts the second and third headline on the same page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Paginated HTML</title>
<style type="text/css" media="print">
div.page
{
page-break-after: always;
page-break-inside: avoid;
}
</style>
</head>
<body>
<div class="page">
<h1>This is Page 1</h1>
</div>
<table>
<tr>
<td>
<div class="page">
<h1>This is Page 2</h1>
</div>
<div class="page">
<h1>This is, sadly, still Page 2</h1>
</div>
</td>
</tr>
</table>
</body>
</html>
Chrome's implementation is (dubiously) allowed given the CSS specification - you can see more here: http://www.google.com/support/forum/p/Chrome/thread?tid=32f9d9629d6f6789&hl=en
Use the 'EntireColumn' property, that's what it is there for. C# snippet, but should give you a good indication of how to do this:
string rangeQuery = "A1:A1";
Range range = workSheet.get_Range(rangeQuery, Type.Missing);
range = range.EntireColumn;
Yes, using System.Reflection
:
using System.Reflection;
...
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
pi.SetValue(myObject, "Bob", null);
I had same problem. After trying all these methods without success I did the following:
tail -f the-mysql-or-maria-db-error-file.err
in another console:
brew services restart mariadb
I saw the following error:
"MAC HOMEBREW Crash recovery failed. Either correct the problem (if it's, for example, out of memory error) and restart, or delete tc log and start mysqld with"
So I changed the tc.log
extesion to tc.log.txt
and restart mariadb
brew services restart mariadb
and done!
How about the Live method?
$('.add_to_this a').live('click', function() {
alert('hello from binded function call');
});
Still, what you did about looks like it should work. There's another post that looks pretty similar.
Use dates.tolist()
to convert to native datetime objects, then simply access year
. Example:
>>> dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype='datetime64')
>>> [x.year for x in dates.tolist()]
[2010, 2011, 2012]
This is basically the same idea exposed in https://stackoverflow.com/a/35281829/2192272, but using simpler syntax.
Tested with python 3.6 / numpy 1.18.
Thanks HansUp for your answer, it is very helpful and it works!
I found three patterns working in Access, yours is the best, because it works in all cases.
INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM
((class
INNER JOIN person AS cr
ON class.C_P_ClassRep=cr.P_Nr
)
INNER JOIN person AS cr2
ON class.C_P_ClassRep2nd=cr2.P_Nr
)
;
INNER JOIN "chained-set pattern"
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM person AS cr
INNER JOIN ( class
INNER JOIN ( person AS cr2
) ON class.C_P_ClassRep2nd=cr2.P_Nr
) ON class.C_P_ClassRep=cr.P_Nr
;
CROSS JOIN with WHERE
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM class, person AS cr, person AS cr2
WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
;
This can happen if you have gulp misconfigured to add your angular app code more than once. In my case, this was in index.js, and it was adding it as part of the directory of js files (globbed in gulp) before and after my controller declarations. Once I added an exclusion for index.js not to be minified and injected the second time, my app began to work. Another tip if any of the solutions above don't address your problem.
$result=mysql_query("SELECT SUM(column) AS total_value FROM table name WHERE column='value'");
$result=mysql_result($result,0,0);
The following works by starting the jar with a batch file, in case the program runs as a stand alone:
public static void startExtJarProgram(){
String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
ProcessBuilder processBuilder = new ProcessBuilder(extJar);
processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
processBuilder.redirectInput();
try {
final Process process = processBuilder.start();
try {
final int exitStatus = process.waitFor();
if(exitStatus==0){
System.out.println("External Jar Started Successfully.");
System.exit(0); //or whatever suits
}else{
System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
System.exit(1);//whatever
}
} catch (InterruptedException ex) {
System.out.println("InterruptedException: "+ex.getMessage());
}
} catch (IOException ex) {
System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
}
System.out.println("Process Terminated.");
System.exit(0);
}
In the batchfile.bat then we can say:
@echo off
start /min C:\path\to\jarprogram.jar
(i === 0 ? "true" : "false")
See the docs FAQ: "How can I see the raw SQL queries Django is running?"
django.db.connection.queries
contains a list of the SQL queries:
from django.db import connection
print(connection.queries)
Querysets also have a query
attribute containing the query to be executed:
print(MyModel.objects.filter(name="my name").query)
Note that the output of the query is not valid SQL, because:
"Django never actually interpolates the parameters: it sends the query and the parameters separately to the database adapter, which performs the appropriate operations."
From Django bug report #17741.
Because of that, you should not send query output directly to a database.
I had the same issue, unable to resize the image when adjusting browser dimensions.
Bad Code:
html {
background-color: white;
background-image: url("example.png");
background-repeat: no-repeat;
background-attachment: scroll;
background-position: 0% 0%;
}
Good Code:
html {
background-color: white;
background-image: url("example.png");
background-repeat: no-repeat;
background-attachment: scroll;
background-position: 0% 0%;
background-size: contain;
}
The key here is the addition of this element -> background-size: contain;
The only solution that worked for me was the most simple. No additional imports needed.
<a href="#" onClick={() => this.props.history.goBack()}>Back</a>
Tks, IamMHussain
Here is a solution using only a custom adapter with a different view type for the empty situation.
public class EventAdapter extends
RecyclerView.Adapter<EventAdapter.ViewHolder> {
private static final int VIEW_TYPE_EVENT = 0;
private static final int VIEW_TYPE_DATE = 1;
private static final int VIEW_TYPE_EMPTY = 2;
private ArrayList items;
public EventAdapter(ArrayList items) {
this.items = items;
}
@Override
public int getItemCount() {
if(items.size() == 0){
return 1;
}else {
return items.size();
}
}
@Override
public int getItemViewType(int position) {
if (items.size() == 0) {
return VIEW_TYPE_EMPTY;
}else{
Object item = items.get(position);
if (item instanceof Event) {
return VIEW_TYPE_EVENT;
} else {
return VIEW_TYPE_DATE;
}
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
ViewHolder vh;
if (viewType == VIEW_TYPE_EVENT) {
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_event, parent, false);
vh = new ViewHolderEvent(v);
} else if (viewType == VIEW_TYPE_DATE) {
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_event_date, parent, false);
vh = new ViewHolderDate(v);
} else {
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_event_empty, parent, false);
vh = new ViewHolder(v);
}
return vh;
}
@Override
public void onBindViewHolder(EventAdapter.ViewHolder viewHolder,
final int position) {
int viewType = getItemViewType(position);
if (viewType == VIEW_TYPE_EVENT) {
//...
} else if (viewType == VIEW_TYPE_DATE) {
//...
} else if (viewType == VIEW_TYPE_EMPTY) {
//...
}
}
public static class ViewHolder extends ParentViewHolder {
public ViewHolder(View v) {
super(v);
}
}
public static class ViewHolderDate extends ViewHolder {
public ViewHolderDate(View v) {
super(v);
}
}
public static class ViewHolderEvent extends ViewHolder {
public ViewHolderEvent(View v) {
super(v);
}
}
}
This is the only thing that worked for me!
df.loc['C', 'x'] = 10
Learn more about .loc
here.
You can do it the DOM way as well:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}
Some options:
tr
tr -d '\15\32' < windows.txt > unix.txt
OR
tr -d '\r' < windows.txt > unix.txt
perl
perl -p -e 's/\r$//' < windows.txt > unix.txt
sed
sed 's/^M$//' windows.txt > unix.txt
OR
sed 's/\r$//' windows.txt > unix.txt
To obtain ^M
, you have to type CTRL-V
and then CTRL-M
.
For something simple that work for arrays , strings , and objects I builed this function:
function console_testing($var){
$var = json_encode($var,JSON_UNESCAPED_UNICODE);
$output = <<<EOT
<script>
console.log($var);
</script>
EOT;
echo $output;
}
To make a long story short, Java objects have some very peculiar properties.
In general, Java has primitive types (int
, bool
, char
, double
, etc) that are passed directly by value. Then Java has objects (everything that derives from java.lang.Object
). Objects are actually always handled through a reference (a reference being a pointer that you can't touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.
Does this sound strange and confusing? Let's consider how C implements pass by reference and pass by value. In C, the default convention is pass by value. void foo(int x)
passes an int by value. void foo(int *x)
is a function that does not want an int a
, but a pointer to an int: foo(&a)
. One would use this with the &
operator to pass a variable address.
Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation: void foo(int &x)
is called by foo(a)
, where the compiler itself knows that it is a reference and the address of the non-reference a
should be passed. In Java, all variables referring to objects are actually of reference type, in effect forcing call by reference for most intends and purposes without the fine grained control (and complexity) afforded by, for example, C++.
Assuming that your branch is called master
both here and remotely, and that your remote is called origin
you could do:
git reset --hard <commit-hash>
git push -f origin master
However, you should avoid doing this if anyone else is working with your remote repository and has pulled your changes. In that case, it would be better to revert the commits that you don't want, then push as normal.
I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));
while ((line = br.readLine()) != null) {
}
I hope this can help anyone who sees this post.
The following command will do what you asked for "extract the lines between 1234 and 5555" in someFile.
sed -n '1234,5555p' someFile
You can check if a element is disabled or not with this:
if($("#slcCausaRechazo").prop('disabled') == false)
{
//your code to realice
}
Use LINQ Aggregate
method to convert array of integers to a comma separated string
var intArray = new []{1,2,3,4};
string concatedString = intArray.Aggregate((a, b) =>Convert.ToString(a) + "," +Convert.ToString( b));
Response.Write(concatedString);
output will be
1,2,3,4
This is one of the solution you can use if you have not .net 4 installed.
extension UITableView {
/// Reloads a table view without losing track of what was selected.
func reloadDataSavingSelections() {
let selectedRows = indexPathsForSelectedRows
reloadData()
if let selectedRow = selectedRows {
for indexPath in selectedRow {
selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
}
}
}
tableView.reloadDataSavingSelections()
I think this first failed because you are ordering value which is null. If Delivery is a foreign key associated table then you should include this table first, example below:
var itemList = from t in ctn.Items.Include(x=>x.Delivery)
where !t.Items && t.DeliverySelection
orderby t.Delivery.SubmissionDate descending
select t;
Some people are saying it's not possible of downloading files with a batch script without using any JScript or VBScript, etc... But they are definitely wrong!
Here is a simple method that seems to work pretty well for downloading files in your batch scripts. It should be working on almost any file's URL. It is even possible to use a proxy server if you need it.
For downloading files, we can use BITSADMIN.EXE from the Windows system. There is no need for downloading/installing anything or using any JScript or VBScript, etc. Bitsadmin.exe is present on most Windows versions, probably from XP to Windows 10.
Enjoy!
USAGE:
You can use the BITSADMIN command directly, like this:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND "http://example.com/File.zip" "C:\Downloads\File.zip"
Proxy Server:
For connecting using a proxy, use this command before downloading.
bitsadmin /setproxysettings mydownloadjob OVERRIDE "proxy-server.com:8080"
Click this LINK if you want more info about BITSadmin.exe
TROUBLESHOOTING:
If you get this error: "Unable to connect to BITS - 0x80070422"
Make sure the windows service "Background Intelligent Transfer Service (BITS)" is enabled and try again. (It should be enabled by default.)
CUSTOM FUNCTIONS
Call :DOWNLOAD_FILE "URL"
Call :DOWNLOAD_PROXY_ON "SERVER:PORT"
Call :DOWNLOAD_PROXY_OFF
I made these 3 functions for simplifying the bitsadmin commands. It's easier to use and remember. It can be particularly useful if you are using it multiple times in your scripts.
PLEASE NOTE...
Before using these functions, you will first need to copy them from CUSTOM_FUNCTIONS.CMD to the end of your script. There is also a complete example: DOWNLOAD-EXAMPLE.CMD
:DOWNLOAD_FILE "URL"
The main function, will download files from URL.
:DOWNLOAD_PROXY_ON "SERVER:PORT"
(Optional) You can use this function if you need to use a proxy server.
Calling the :DOWNLOAD_PROXY_OFF function will disable the proxy server.
EXAMPLE:
CALL :DOWNLOAD_PROXY_ON "proxy-server.com:8080"
CALL :DOWNLOAD_FILE "http://example.com/File.zip" "C:\Downloads\File.zip"
CALL :DOWNLOAD_PROXY_OFF
CUSTOM_FUNCTIONS.CMD
:DOWNLOAD_FILE
rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF
:DOWNLOAD_PROXY_ON
rem FUNCTION FOR USING A PROXY SERVER:
bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF
:DOWNLOAD_PROXY_OFF
rem FUNCTION FOR STOP USING A PROXY SERVER:
bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF
DOWNLOAD-EXAMPLE.CMD
@ECHO OFF
SETLOCAL
rem FOR DOWNLOADING FILES, THIS SCRIPT IS USING THE "BITSADMIN.EXE" SYSTEM FILE.
rem IT IS PRESENT ON MOST WINDOWS VERSION, PROBABLY FROM WINDOWS XP TO WINDOWS 10.
:SETUP
rem URL (5MB TEST FILE):
SET "FILE_URL=http://ipv4.download.thinkbroadband.com/5MB.zip"
rem SAVE IN CUSTOM LOCATION:
rem SET "SAVING_TO=C:\Folder\5MB.zip"
rem SAVE IN THE CURRENT DIRECTORY
SET "SAVING_TO=5MB.zip"
SET "SAVING_TO=%~dp0%SAVING_TO%"
:MAIN
ECHO.
ECHO DOWNLOAD SCRIPT EXAMPLE
ECHO.
ECHO FILE URL: "%FILE_URL%"
ECHO SAVING TO: "%SAVING_TO%"
ECHO.
rem UNCOMENT AND MODIFY THE NEXT LINE IF YOU NEED TO USE A PROXY SERVER:
rem CALL :DOWNLOAD_PROXY_ON "PROXY-SERVER.COM:8080"
rem THE MAIN DOWNLOAD COMMAND:
CALL :DOWNLOAD_FILE "%FILE_URL%" "%SAVING_TO%"
rem UNCOMMENT NEXT LINE FOR DISABLING THE PROXY (IF YOU USED IT):
rem CALL :DOWNLOAD_PROXY_OFF
:RESULT
ECHO.
IF EXIST "%SAVING_TO%" ECHO YOUR FILE HAS BEEN SUCCESSFULLY DOWNLOADED.
IF NOT EXIST "%SAVING_TO%" ECHO ERROR, YOUR FILE COULDN'T BE DOWNLOADED.
ECHO.
:EXIT_SCRIPT
PAUSE
EXIT /B
rem FUNCTIONS SECTION
:DOWNLOAD_FILE
rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF
:DOWNLOAD_PROXY_ON
rem FUNCTION FOR USING A PROXY SERVER:
bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF
:DOWNLOAD_PROXY_OFF
rem FUNCTION FOR STOP USING A PROXY SERVER:
bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF
I strongly suggest placing this somewhere in your project:
extension String {
func trim() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
func trim(withSet: NSCharacterSet) -> String {
return self.stringByTrimmingCharactersInSet(withSet)
}
}
Also with dict
a = []
b = {1:'one'}
a.append(dict(b))
print a
b[1]='iuqsdgf'
print a
result
[{1: 'one'}]
[{1: 'one'}]
You need to set
WindowStyle="None"
, AllowsTransparency="True"
and optionally ResizeMode="NoResize"
and then set the Style
property of the window to your custom window style, where you design the appearance of the window (title bar, buttons, border) to anything you want and display the window contents in a ContentPresenter
.
This seems to be a good article on how you can achieve this, but there are many other articles on the internet.
It is possible to find where any additional SD cards are mounted by reading /proc/mounts
(standard Linux file) and cross-checking against vold data (/system/etc/vold.conf
). And note, that the location returned by Environment.getExternalStorageDirectory()
may not appear in vold configuration (in some devices it's internal storage that cannot be unmounted), but still has to be included in the list. However we didn't find a good way to describe them to the user.
You can use this code instead.
<div id="" style="overflow-y:scroll; overflow-x:hidden; height:400px;">
overflow-x: The overflow-x property specifies what to do with the left/right edges of the content - if it overflows the element's content area.
overflow-y: The overflow-y property specifies what to do with the top/bottom edges of the content - if it overflows the element's content area.
Values
visible: Default value. The content is not clipped, and it may be rendered outside the content box.
hidden: The content is clipped - and no scrolling mechanism is provided.
scroll: The content is clipped and a scrolling mechanism is provided.
auto: Should cause a scrolling mechanism to be provided for overflowing boxes.
initial: Sets this property to its default value.
inherit Inherits this property from its parent element.
You haven't provided enough context to provide an accurate answer (i.e. how do you want to handle identical keys in multiple dicts?)
One answer is to iterate the list, and attempt to get 'd'
mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
myvalues = [i['d'] for i in mylist if 'd' in i]
Another answer is to access the dict directly (by list index), though you have to know that the key is present
mylist[1]['d']
This worked for me: Top Menu -> File -> Invalidate Caches/Restart
this will work as well
require_once(realpath($_SERVER["DOCUMENT_ROOT"]) .'/mysite/php/includes/dbconn.inc');
I would make the class final
and every method would be static
.
So the class cannot be extended and the methods can be called by Classname.methodName
. If you add members, be sure that they work thread safe ;)
Go to Settings => Plugins => Search Plugins in Marketplace
Search by material theme
and download and restart it. it is a good theme.
In the market place, you can also search by theme
and it will list all the themes and you can download any themes. You no need to find themes and download and import it. You can also remove the theme very easily. thanks
if you have
<span class="label label-default">New</span>
just add the style="font-size:XXpx;", ej.
<span class="label label-default" style="font-size:15px;">New</span>
I was with the same problem except with a slight difference, the version of PHPMailer 6.0, by the good friend avs099 I know that the new version of PHPMailer since February 2018 does not support the autoload, and had a serious problem to instantiate the libraries with the namespace in MVC, I leave the code for those who need it.
//Controller
protected function getLibraryWNS($libreria) {
$rutaLibreria = ROOT . 'libs' . DS . $libreria . '.php';
if(is_readable($rutaLibreria)){
require_once $rutaLibreria;
echo $rutaLibreria . '<br/>';
}
else{
throw new Exception('Error de libreria');
}
}
//loginController
public function enviarEmail($email, $nombre, $asunto, $cuerpo){
//Import the PHPMailer class into the global namespace
$this->getLibraryWNS('PHPMailer');
$this->getLibraryWNS('SMTP');
//Create a new PHPMailer instance
$mail = new \PHPMailer\PHPMailer\PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// $mail->SMTPDebug = 0; // 0 = off (for production use), 1 = client messages, 2 = client and server messages Godaddy POR CONFIRMAR
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
//Whether to use SMTP authentication
$mail->SMTPAuth = true; // authentication enabled
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'ssl'; //Seguridad Correo Gmail
//Set the hostname of the mail server
$mail->Host = "smtp.gmail.com"; //Host Correo Gmail
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 465; //587;
//Verifica si el servidor acepta envios en HTML
$mail->IsHTML(true);
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = '[email protected]';
//Password to use for SMTP authentication
$mail->Password = 'tucontraseña';
//Set who the message is to be sent from
$mail->setFrom('[email protected]','Creador de Páginas Web');
$mail->Subject = $asunto;
$mail->Body = $cuerpo;
//Set who the message is to be sent to
$mail->addAddress($email, $nombre);
//Send the message, check for errors
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
} else {
echo "Message has been sent";
return true;
}
var app = angular.module('myApp', []);_x000D_
app.controller('myCtrl', function($scope) {_x000D_
_x000D_
$scope.minus = function() { _x000D_
_x000D_
var a = Number($scope.a || 0);_x000D_
var b = Number($scope.b || 0);_x000D_
$scope.sum1 = a-b;_x000D_
// $scope.sum = $scope.sum1+1; _x000D_
alert($scope.sum1);_x000D_
}_x000D_
_x000D_
$scope.add = function() { _x000D_
_x000D_
var c = Number($scope.c || 0);_x000D_
var d = Number($scope.d || 0);_x000D_
$scope.sum2 = c+d;_x000D_
alert($scope.sum2);_x000D_
}_x000D_
});
_x000D_
<head>_x000D_
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
<h3>Using Double Negation</h3>_x000D_
_x000D_
<p>First Number:_x000D_
<input type="text" ng-model="a" />_x000D_
</p>_x000D_
<p>Second Number:_x000D_
<input type="text" ng-model="b" />_x000D_
</p>_x000D_
<button id="minus" ng-click="minus()">Minus</button>_x000D_
<!-- <p>Sum: {{ a - b }}</p> -->_x000D_
<p>Sum: {{ sum1 }}</p>_x000D_
_x000D_
<p>First Number:_x000D_
<input type="number" ng-model="c" />_x000D_
</p>_x000D_
<p>Second Number:_x000D_
<input type="number" ng-model="d" />_x000D_
</p>_x000D_
<button id="minus" ng-click="add()">Add</button>_x000D_
<p>Sum: {{ sum2 }}</p>_x000D_
</div>
_x000D_
I'm surprised that nobody suggested guava solution yet:
com.google.common.collect.Iterables.get(collection, 0)
// or
com.google.common.collect.Iterables.get(collection, 0, defaultValue)
// or
com.google.common.collect.Iterables.getFirst(collection, defaultValue)
or if you expect single element:
com.google.common.collect.Iterables.getOnlyElement(collection, defaultValue)
// or
com.google.common.collect.Iterables.getOnlyElement(collection)
I figured out why.
If the client who issued the RESTORE DATABASE
command disconnects during the restore, the restore will be stuck.
It's odd that the server, when told to restore a database by a client connection, will not finish the restore unless the client stays connected the entire time.
:ls
for list of open buffers
:bp
previous buffer:bn
next buffer:bn
(n
a number) move to n'th buffer:b <filename-part>
with tab-key providing auto-completion (awesome !!)In some versions of vim, bn
and bp
are actually bnext
and bprevious
respectively. Tab auto-complete is helpful in this case.
Or when you are in normal mode, use ^
to switch to the last file you were working on.
Plus, you can save sessions of vim
:mksession! ~/today.ses
The above command saves the current open file buffers and settings to ~/today.ses
. You can load that session by using
vim -S ~/today.ses
No hassle remembering where you left off yesterday. ;)
An answer for the future: CSS 4 will probably contain the revert keyword, which reverts a property to its value from the user or user-agent stylesheet [source]. As of writing this, only Safari supports this – check here for updates on browser support.
In your case you would use:
.my_container ol, .my_container ul {
list-style: revert;
}
See also this other answer with some more details.
Put that file in assets.
For project created in Android Studio project you need to create assets folder under the main folder.
Read that file as:
public String loadJSONFromAsset(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("file_name.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and then you can simply read this string
return by this function as
JSONObject obj = new JSONObject(json_return_by_the_function);
For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html
Hope you will get what you want.
pip install pyyaml
If you don't have pip, run easy_install pip
to install pip, which is the go-to package installer - Why use pip over easy_install?. If you prefer to stick with easy_install, then easy_install pyyaml
Or, once it's already in SSIS, you could create a derived column (as part of some data flow task) with:
(DT_I8)FLOOR((DT_R8)systemDateTime)
But you'd have to test to doublecheck.
Not related to question but in case if someone is passing the string as an argument to bash script this might help.
Use:
./bash_script.sh "path\to\file"
Instead of:
./bash_script.sh path\to\file
For your reference.
I did it right now with one of my grids.
here is the example which i used to retrive and parse json data from s3.
var params = {Bucket: BUCKET_NAME, Key: KEY_NAME};
new AWS.S3().getObject(params, function(err, json_data)
{
if (!err) {
var json = JSON.parse(new Buffer(json_data.Body).toString("utf8"));
// PROCESS JSON DATA
......
}
});
If you have seen important TV machine, TV connections and TV color tube is hidden inside the TV case which is not been exposed for viewers like us and exposed only neccessary things of a TV like TV Channel keys, TV volume keys, ON/OFF switch, Cable Switch and TV remote control for viewers to use it.This means TV machine, TV connections and TV color tube is an unwanted data and not needed for viewers to see is been hidden from outside the world
So encapsulation means hiding the important features of a class which is not been needed to be exposed outside of a class and exposing only necessary things of a class. Here hidden part of a class acts like Encapsulation and exposed part of a class acts like Abstraction.
git stash
is your friend.
If you have not made the commit yet, just run git stash
. This will save away all of your changes.
Switch to the branch you want the changes on and run git stash pop
.
There are lots of uses for git stash. This is certainly one of the more useful reasons.
An example:
# work on some code
git stash
git checkout correct-branch
git stash pop
I was frustrated trying to connect my Android App to my RESTful service using https. Also I was a bit annoyed about all the answers that suggested to disable certificate checking altogether. If you do so, whats the point of https?
After googled about the topic for a while, I finally found this solution where external jars are not needed, just Android APIs. Thanks to Andrew Smith, who posted it on July, 2014
/**
* Set up a connection to myservice.domain using HTTPS. An entire function
* is needed to do this because myservice.domain has a self-signed certificate.
*
* The caller of the function would do something like:
* HttpsURLConnection urlConnection = setUpHttpsConnection("https://littlesvr.ca");
* InputStream in = urlConnection.getInputStream();
* And read from that "in" as usual in Java
*
* Based on code from:
* https://developer.android.com/training/articles/security-ssl.html#SelfSigned
*/
public static HttpsURLConnection setUpHttpsConnection(String urlString)
{
try
{
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// My CRT file that I put in the assets folder
// I got this file by following these steps:
// * Go to https://littlesvr.ca using Firefox
// * Click the padlock/More/Security/View Certificate/Details/Export
// * Saved the file as littlesvr.crt (type X.509 Certificate (PEM))
// The MainActivity.context is declared as:
// public static Context context;
// And initialized in MainActivity.onCreate() as:
// MainActivity.context = getApplicationContext();
InputStream caInput = new BufferedInputStream(MainActivity.context.getAssets().open("littlesvr.crt"));
Certificate ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
return urlConnection;
}
catch (Exception ex)
{
Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
return null;
}
}
It worked nice for my mockup App.
As others have suggested, you are not clearly explaining your problem, what you are trying to do, or what your expectations are as to what this function is actually supposed to do.
If I have understood correctly, then you are expecting this function to refresh the page for you (you actually use the term "reloads the browser").
But this function is not intended to reload the browser.
All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.
Normally, this is used in conjunction with AJAX calls (which refresh only a part of the page).
For example, if a user does a search "CATS" in one of your search boxes, and the results of the search (presumably cute pictures of cats) are loaded back via AJAX, into the lower-right of your page -- then your page state will not be changed. In other words, in the near future, when the user decides that he wants to go back to his search for "CATS", he won't be able to, because the state doesn't exist in his history. He will only be able to click back to your blank search box.
Hence the need for the function
history.pushState({},"Results for `Cats`",'url.html?s=cats');
It is intended as a way to allow the programmer to specifically define his search into the user's history trail. That's all it is intended to do.
When the function is working properly, the only thing you should expect to see, is the address in your browser's address-bar change to whatever you specify in your URL.
If you already understand this, then sorry for this long preamble. But it sounds from the way you pose the question, that you have not.
As an aside, I have also found some contradictions between the way that the function is described in the documentation, and the way it works in reality. I find that it is not a good idea to use blank or empty values as parameters.
See my answer to this SO question. So I would recommend putting a description in your second parameter. From memory, this is the description that the user sees in the drop-down, when he clicks-and-holds his mouse over "back" button.
Good solution to extend native functionality by extensions
import UIKit
extension UIImage {
convenience init?(url: URL?) {
guard let url = url else { return nil }
do {
self.init(data: try Data(contentsOf: url))
} catch {
print("Cannot load image from url: \(url) with error: \(error)")
return nil
}
}
}
Convenience initializer is failable and accepts optional URL
– approach is safe.
imageView.image = UIImage(url: URL(string: "some_url.png"))
If you are using spring-boot, this is the best answer.
I feel that @PostConstruct
and other various life cycle interjections are round-about ways. These can lead directly to runtime issues or cause less than obvious defects due to unexpected bean/context lifecycle events. Why not just directly invoke your bean using plain Java? You still invoke the bean the 'spring way' (eg: through the spring AoP proxy). And best of all, it's plain java, can't get any simpler than that. No need for context listeners or odd schedulers.
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext app = SpringApplication.run(DemoApplication.class, args);
MyBean myBean = (MyBean)app.getBean("myBean");
myBean.invokeMyEntryPoint();
}
}
Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:
<profile>
<id>alternateBuildDir</id>
<activation>
<property>
<name>alt.build.dir</name>
</property>
</activation>
<build>
<directory>${alt.build.dir}</directory>
</build>
</profile>
Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.
You said you didn't want to use a translucent Activity, but that seems to be the best way to do this:
Theme.Translucent.NoTitleBar
.setContentView()
.onCreate()
, start your Service with startService()
.finish()
once you've started the Service.In other words, your Activity doesn't have to be visible; it can simply make sure your Service is running and then exit, which sounds like what you want.
I would highly recommend showing at least a Toast notification indicating to the user that you are launching the Service, or that it is already running. It is very bad user experience to have a launcher icon that appears to do nothing when you press it.
Use scp priv_key.pem source user@host:target
if you need to connect using a private key.
or if using pscp then use pscp -i priv_key.ppk source user@host:target
if (row.Columns.Contains("US_OTHERFRIEND"))
The DELIMITER statement changes the standard delimiter which is semicolon ( ;) to another. The delimiter is changed from the semicolon( ;) to double-slashes //.
Why do we have to change the delimiter?
Because we want to pass the stored procedure, custom functions etc. to the server as a whole rather than letting mysql tool to interpret each statement at a time.
Open Sublime Text console ? paste in opened field:
sublime.packages_path()
? Enter. You get result in console output.
This answer is relevant for April 2018. In the future, the data of this answer may be obsolete.
I'm not recommended @osiris answer. Arguments:
Packages
folder.You go into your router configuration and forward port 80 to the LAN IP of the computer running the web server.
Then anyone outside your network (but not you inside the network) can access your site using your WAN IP address (whatismyipcom).
I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.
A really simple solution:
public int numLength(int n) {
for (int length = 1; n % Math.pow(10, length) != n; length++) {}
return length;
}
You can save an html file with the extension 'xls' and accents will work (pre 2007 at least).
Example: save this (using Save As utf8 in Notepad) as test.xls:
<html>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<table>
<tr>
<th>id</th>
<th>name</th>
</tr>
<tr>
<td>4</td>
<td>Hélène</td>
</tr>
</table>
</html>
And if anyone is wondering how to do this in swift
:
if let myDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
myDelegate.someMethod()
}
Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct()
within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).
So you want to:
Inspired by this answer, here's the adapted version of your script:
#!/usr/bin/env bash
different_user=deploy
useradd -m -s /bin/bash "$different_user"
echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo
echo "Switching user to $different_user"
sudo -u "$different_user" -i /bin/bash - <<-'EOF'
echo "Current user: $(id)"
echo "Current directory: $(pwd)"
EOF
echo
echo "Switched back to $(whoami)"
different_user_home="$(eval echo ~"$different_user")"
echo "$different_user home directory: $different_user_home"
When you run it, you should get the following:
Current user: root
Current directory: /root
Switching user to deploy
Current user: uid=1003(deploy) gid=1003(deploy) groups=1003(deploy)
Current directory: /home/deploy
Switched back to root
deploy home directory: /home/deploy
The Java code given by Dommer above gives slightly incorrect results but the small errors add up if you are processing say a GPS track. Here is an implementation of the Haversine method in Java which also takes into account height differences between two points.
/**
* Calculate distance between two points in latitude and longitude taking
* into account height difference. If you are not interested in height
* difference pass 0.0. Uses Haversine method as its base.
*
* lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters
* el2 End altitude in meters
* @returns Distance in Meters
*/
public static double distance(double lat1, double lat2, double lon1,
double lon2, double el1, double el2) {
final int R = 6371; // Radius of the earth
double latDistance = Math.toRadians(lat2 - lat1);
double lonDistance = Math.toRadians(lon2 - lon1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = el1 - el2;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return Math.sqrt(distance);
}
After a bit of research we came up with the following list of headers that seemed to cover most browsers:
In ASP.NET we added these using the following snippet:
Response.ClearHeaders();
Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1
Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0
Response.AppendHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.0
Found from: http://forums.asp.net/t/1013531.aspx
https://onpyth.blogspot.com/2019/08/check-ping-connectivity-to-multiple-host.html
Above link is to create Python script for checking connectivity. You can use similar method and use:
ping -w 1 -c 1 "IP Address"
Command to create bash script.
When you see the "Cannot evaluate expression because the code of the current method is optimized." message after issuing a Debugger.Break()
statement then please make sure you press F10 to step to the next statement.
Once stepped to the next statement, and assuming you are running a Debug build, this message should disappear.
Why not just inspect the generated markup, note the class on the button of choice and style it yourself?
Sometimes you might add a state value from props in constructor or componentDidMount, you might need to call setState when the props changed but the component has already mounted so componentDidMount will not execute and neither will constructor; in this particular case, you can use componentDidUpdate since the props have changed, you can call setState in componentDidUpdate with new props.
.NET Data Provider -- Default Relative Path -- Standard Connection
using System.Data.SqlClient;
var conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|DataBaseName.mdf;"conn.Open();
.NET Data Provider -- Default Relative Path -- Trusted Connection
using System.Data.SqlClient;
var conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|DataBaseName.mdf;" conn.Open();
.NET Data Provider -- Custom Relative Path -- Standard Connection
using System.Data.SqlClient;
AppDomain.CurrentDomain.SetData(
"DataDirectory", "C:\MyPath\");
var conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|DataBaseName.mdf;" conn.Open();
.NET Data Provider -- Custom Relative Path -- Trusted Connection
using System.Data.SqlClient;
AppDomain.CurrentDomain.SetData(
"DataDirectory", "C:\MyPath\");
var conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|DataBaseName.mdf;" conn.Open();
Download the Visual C++ Redistributable 2015
Updated links to VC++ file:
I'd create a cte and do an inner join. It's not efficient but it's convenient
with table as (
SELECT DATE, STATUS, TITLE, ROW_NUMBER()
OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM TABLE)
select *
from table t
join select(
max(Row_Num) as Row_Num
,DATE
,STATUS
,TITLE
from table
group by date, status, title) t2
on t2.Row_Num = t.Row_Num and t2
and t2.date = t.date
and t2.title = t.title
The comparison needs to be evaluated fully inside EL ${ ... }
, not outside.
<c:if test="${values.type eq 'object'}">
As to the docs, those ${}
things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.
<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass()
and then Class#getSimpleName()
instead of adding a custom getter.
<c:forEach items="${list}" var="value">
<c:if test="${value['class'].simpleName eq 'Object'}">
<!-- code here -->
</c:if>
</c:forEeach>
select T.TABLE_NAME, T.TABLESPACE_NAME, t.avg_row_len*t.num_rows from dba_tables t
order by T.TABLE_NAME asc
See e.g. http://www.dba-oracle.com/t_script_oracle_table_size.htm for more options
Had a similar problem on Centos 7. When I tried to apply the solution prescribed by Sorin, I started moving in cycles. First I had a permission {write} denied. Then when I solved that I had a permission { connectto } denied. Then back again to permission {write } denied.
Following @Sid answer above of checking the flags using getsebool -a | grep httpd
and toggling them I found that in addition to the httpd_can_network_connect being off. http_anon_write was also off resulting in permission denied write and permission denied {connectto}
type=AVC msg=audit(1501830505.174:799183): avc:
denied { write } for pid=12144 comm="nginx" name="myroject.sock"
dev="dm-2" ino=134718735 scontext=system_u:system_r:httpd_t:s0
tcontext=system_u:object_r:default_t:s0 tclass=sock_file
Obtained using sudo cat /var/log/audit/audit.log | grep nginx | grep denied as explained above.
So I solved them one at a time, toggling the flags on one at a time.
setsebool httpd_can_network_connect on -P
Then running the commands specified by @sorin and @Joseph above
sudo cat /var/log/audit/audit.log | grep nginx | grep denied |
audit2allow -M mynginx
sudo semodule -i mynginx.pp
Basically you can check the permissions set on setsebool and correlate that with the error obtained from grepp'ing' audit.log nginx, denied
Your main fun will call firstFun then on complete of it your next fun will call.
async firstFunction() {
const promise = new Promise((resolve, reject) => {
for (let i = 0; i < 5; i++) {
// do something
console.log(i);
if (i == 4) {
resolve(i);
}
}
});
const result = await promise;
}
second() {
this.firstFunction().then( res => {
// third function call do something
console.log('Gajender here');
});
}
You might need to set permissions at the database level that allows your schema owner to restore the dump.
For example, say you were creating a web application to list and display recipes. You might want your customers to be able to sort the list, display features of the recipes, and so on before they choose the recipe to open. In order to do this, you need to associate things like cooking time, primary ingredient, meal position, and so on right inside the list elements for the recipes.
<li><a href="recipe1.html">Borscht</a></li>
<li><a href="recipe2.html">Chocolate Mousse</a></li>
<li><a href="recipe3.html">Almond Radiccio Salad</a></li>
<li><a href="recipe4.html">Deviled Eggs</a></li>
In order to get that information into the page, you could do many different things. You could add comments to each LI element, you could add rel attributes to the list items, you could place all the recipes in separate folders based on time, meal, and ingredient (i.e. ). The solution that most developers took was to use class attributes to store information about the current element. This has several advantages:
But there are some major drawbacks to this method:
All the other methods I suggested had these problems as well as others. But since it was the only way to quickly and easily include data, that’s what we did. HTML5 Data Attributes to the Rescue
HTML5 added a new type of attribute to any element—the custom data element (data-*). These are custom (denoted by the *) attributes that you can add to your HTML elements to define any type of data you want. They consist of two parts:
Attribute Name This is the name of the attribute. It must be at least one lowercase character and have the prefix data-. For example: data-main-ingredient, data-cooking-time, data-meal. This is the name of your data.
Attribute Vaule Like any other HTML attribute, you include the data itself in quotes separated by an equal sign. This data can be any string that is valid on a web page. For example: data-main-ingredient="chocolate".
You can then apply these data attributes to any HTML element you want. For example, you could define the information in the example list above:
<li data-main-ingredient="beets" data-cooking-time="1 hour" data-meal="dinner"><a href="recipe1.html">Borscht</a></li>
<li data-main-ingredient="chocolate" data-cooking-time="30 minutes" data-meal="dessert"><a href="recipe2.html">Chocolate Mousse</a></li>
<li data-main-ingredient="radiccio" data-cooking-time="20 minutes" data-meal="dinner"><a href="recipe1.html">Almond Radiccio Salad</a></li>
<li data-main-ingredient="eggs" data-cooking-time="15 minutes" data-meal="appetizer"><a href="recipe1.html">Deviled Eggs</a></li>
Once you have that information in your HTML, you will be able to access it with JavaScript and manipulate the page based on that data.
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
These are deprecated use the following..
// Connects to your Database
$link = mysqli_connect("localhost", "root", "", "");
and to insert data use the following
$sql = "INSERT INTO Table-Name (Column-Name)
VALUES ('$filename')" ;
Use the <apply> task.
It executes a command once for each file. Specify the files by means of filesets or any other resource. <apply> is built-in; no additional dependency needed; no custom task implementation needed.
It's also possible to run the command only once, appending all files as arguments in one go. Use the parallel attribute to switch the behaviour.
Sorry for being late a year.
you should check the radiobutton in the radiogroup like this:
radiogroup.check(IdOfYourButton)
Of course you first have to set an Id to your radiobuttons
EDIT: i forgot, radioButton.getId()
works as well, thx Ramesh
EDIT2:
android:checkedButton="@+id/my_radiobtn"
works in radiogroup xml
I am making an assumption that there is a counter already in place. in $i which is incremented at the end of a loop, This works for me using a shorthand query.
$row_pos = ($i & 1) ? 'odd' : 'even';
So what does this do, well it queries the statement we are making in essence $i is odd, depending whether its true or false will decide what gets returned. The returned value populates our variable $row_pos
My use of this is to place it inside the foreach loop, right before i need it, This makes it a very efficient one liner to give me the appropriate class names, this is because i already have a counter for the id's to make use of later in the program. This is a brief example of how i will use this part.
<div class='row-{$row_pos}'> random data <div>
This gives me odd and even classes on each row so i can use the correct class and stripe my printed results down the page.
The full example of what i use note the id has the counter applied to it and the class has my odd/even result applied to it.:
$i=0;
foreach ($a as $k => $v) {
$row_pos = ($i & 1) ? 'odd' : 'even';
echo "<div id='A{$i}' class='row-{$row_pos}'>{$v['f_name']} {$v['l_name']} - {$v['amount']} - {$v['date']}</div>\n";
$i++;
}
in summary, this gives me a very simple way to create a pretty table.
You can do it in a shorthand as:
_.uniq(foo, 'a')
There must be also an answer for people who want a hassle free https on ec2 for mainly demo and testing purposes, one way they can achieve that very fast is:
With my answer here which describes How you can achieve https for testing purposes in minutes with EC2 without the hassle of creating certificates
Try to find out ID of your form element in generated aspx, and you can change target like...
getElementByID('theForm').target = '_blank' or 'myNewWindow'
The problem is that the evaluation of Click()
times out on your build env.. you might want to dig into what happens on Click()
.
Also, try adding Retrys for the Click()
because occssionally the evaluations take longer time depending on network speeds, etc
In a project of mine I wrap Text
instances around Container
s. This particular code sample features two stacked Text objects.
Here's a code sample.
//80% of screen width
double c_width = MediaQuery.of(context).size.width*0.8;
return new Container (
padding: const EdgeInsets.all(16.0),
width: c_width,
child: new Column (
children: <Widget>[
new Text ("Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 ", textAlign: TextAlign.left),
new Text ("Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2", textAlign: TextAlign.left),
],
),
);
[edit] Added a width constraint to the container
(copy-paste/adapted from https://stackoverflow.com/a/24048772/1733117).
First you can subclass urllib2.BaseHandler
or urllib2.HTTPBasicAuthHandler
, and implement http_request
so that each request has the appropriate Authorization
header.
import urllib2
import base64
class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
'''Preemptive basic auth.
Instead of waiting for a 403 to then retry with the credentials,
send the credentials if the url is handled by the password manager.
Note: please use realm=None when calling add_password.'''
def http_request(self, req):
url = req.get_full_url()
realm = None
# this is very similar to the code from retry_http_basic_auth()
# but returns a request object.
user, pw = self.passwd.find_user_password(realm, url)
if pw:
raw = "%s:%s" % (user, pw)
auth = 'Basic %s' % base64.b64encode(raw).strip()
req.add_unredirected_header(self.auth_header, auth)
return req
https_request = http_request
Then if you are lazy like me, install the handler globally
api_url = "http://api.foursquare.com/"
api_username = "johndoe"
api_password = "some-cryptic-value"
auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(
realm=None, # default realm.
uri=api_url,
user=api_username,
passwd=api_password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
sort_mixed
Object.defineProperty(Array.prototype,"sort_mixed",{
value: function () { // do not use arrow function
var N = [], L = [];
this.forEach(e => {
Number.isFinite(e) ? N.push(e) : L.push(e);
});
N.sort((a, b) => a - b);
L.sort();
[...N, ...L].forEach((v, i) => this[i] = v);
return this;
})
try a =[1,'u',"V",10,4,"c","A"].sort_mixed(); console.log(a)
For those who needs to stop all Threads running and re-run all of them when any one of them is stopped on an Exception:
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// could be any function
getStockHistory();
}
public void getStockHistory() {
// fill a list of symbol to be scrapped
List<String> symbolListNYSE = stockEntityRepository
.findByExchangeShortNameOnlySymbol(ContextRefreshExecutor.NYSE);
storeSymbolList(symbolListNYSE, ContextRefreshExecutor.NYSE);
}
private void storeSymbolList(List<String> symbolList, String exchange) {
int total = symbolList.size();
// I create a list of Thread
List<Thread> listThread = new ArrayList<Thread>();
// For each 1000 element of my scrapping ticker list I create a new Thread
for (int i = 0; i <= total; i += 1000) {
int l = i;
Thread t1 = new Thread() {
public void run() {
// just a service that store in DB my ticker list
storingService.getAndStoreStockPrice(symbolList, l, 1000,
MULTIPLE_STOCK_FILL, exchange);
}
};
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable exception) {
// stop thread if still running
thread.interrupt();
// go over every thread running and stop every one of them
listThread.stream().forEach(tread -> tread.interrupt());
// relaunch all the Thread via the main function
getStockHistory();
}
};
t1.start();
t1.setUncaughtExceptionHandler(h);
listThread.add(t1);
}
}
To sum up :
You have a main function that create multiple thread, each of them has UncaughtExceptionHandler which is trigger by any Exception inside of a thread. You add every Thread to a List. If a UncaughtExceptionHandler is trigger it will loop through the List, stop every Thread and relaunch the main function recreation all the Thread.
We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as x % y
. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number.
This function will return a boolean, True
or False
, depending on whether n
is a whole number.
def is_whole(n):
return n % 1 == 0
It is easy, but the Google API examples give you detailed explanation with how you can get the map to display the entered location. For only autocomplete feature, you can do something like this.
First, enable Google Places API Web Service. Get the API key. You will have to use it in the script tag in html file.
<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>
Use script file to load the autocomplete class. Your scripts.js file will look something like this.
// scripts.js custom js file
$(document).ready(function () {
google.maps.event.addDomListener(window, 'load', initialize);
});
function initialize() {
var input = document.getElementById('location');
var autocomplete = new google.maps.places.Autocomplete(input);
}
for(int i=0;i<n;i++)
{
for(int j=str[i].length();j<4;j++)
str[i]="0".concat(str[i]);
}
str[i].length()
is length of number say 2 in binary is 01 which is length 2
change 4 to desired max length of number. This can be optimized to O(n).
by using continue.
I would look for an existing mapping of your 3rd party JS libraries that support Script# or SharpKit. Users of these C# to .js cross compilers will have faced the problem you now face and might have published an open source program to scan your 3rd party lib and convert into skeleton C# classes. If so hack the scanner program to generate TypeScript in place of C#.
Failing that, translating a C# public interface for your 3rd party lib into TypeScript definitions might be simpler than doing the same by reading the source JavaScript.
My special interest is Sencha's ExtJS RIA framework and I know there have been projects published to generate a C# interpretation for Script# or SharpKit
The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:
Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:
var foomodule = require('foo');
// do something with fooModule
What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...
var module = require(path); // Call RequireJS require
...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;
var moduleName = 'foo';
require([moduleName], function(fooModule){
// do something with fooModule
})
Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:
define(['dyn_modules'], function (dynModules) {
require(dynModules, function(){
// use arguments since you don't know how many modules you're getting in the callback
for (var i = 0; i < arguments.length; i++){
var mymodule = arguments[i];
// do something with mymodule...
}
});
});
EDIT: From your own answer, I see you're using underscore/lodash, so using _.values
and _.object
can simplify the looping through arguments array as above.
First add the new files:
svn add fileName
Then commit all new and modified files
svn ci <files_separated_by_space> -m "Commit message|ReviewID:XXXX"
If non source files are to be committed then
svn ci <files> -m "Commit msg|ReviewID:NON-SOURCE"
Try this one:
json.dumps(json.loads(df.to_json(orient="records")))
you can use command line query and execute in mssql:
exec xp_cmdshell 'ipconfig'
If you want the ability to change which method is called at run time I would recommend using a delegate: http://www.codeproject.com/KB/cs/delegates_step1.aspx
It will allow you to create an object to store the method to call and you can pass that to your other methods when it's needed.
Since it's mid 2019 and jQuery sometimes takes a backseat to things like VueJS, React etc. Here's a pure vanilla Javascript onload listener option:
<script>
// Replace 'admincheckbox' both variable and ID with whatever suits.
window.onload = function() {
const admincheckbox = document.getElementById("admincheckbox");
admincheckbox.addEventListener('click', function() {
if(admincheckbox.checked){
alert('Checked');
} else {
alert('Unchecked');
}
});
}
</script>
When you make the input, set it to be readonly.
<input type="text" name="datepicker" id="datepicker" readonly="readonly" />
I like Calibri.
The namespace name http://www.w3.org/1999/xhtml
is intended for use in various specifications such as:
Recommendations:
XHTML™ 1.0: The Extensible HyperText Markup Language
XHTML Modularization
XHTML 1.1
XHTML Basic
XHTML Print
XHTML+RDFa
Check here for more detail
If you wrap one stream into another, you don't close intermediate streams, and very important: You don't close them before finishing using the outer streams. Because you would close the outer stream too.
The slick-slide has inner wrapping div which you can use to create spacing between slides without breaking the design:
.slick-list {margin: 0 -5px;}
.slick-slide>div {padding: 0 5px;}
Here is your code for add data into both tableView:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var table1Text: UITextField!
@IBOutlet weak var table2Text: UITextField!
@IBOutlet weak var table1: UITableView!
@IBOutlet weak var table2: UITableView!
var table1Data = ["a"]
var table2Data = ["1"]
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func addData(sender: AnyObject) {
//add your data into tables array from textField
table1Data.append(table1Text.text)
table2Data.append(table2Text.text)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//reload your tableView
self.table1.reloadData()
self.table2.reloadData()
})
table1Text.resignFirstResponder()
table2Text.resignFirstResponder()
}
//delegate methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == table1 {
return table1Data.count
}else if tableView == table2 {
return table2Data.count
}
return Int()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == table1 {
let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = table1Data[row]
return cell
}else if tableView == table2 {
let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = table2Data[row]
return cell
}
return UITableViewCell()
}
}
And your result will be:
JQuery can't append elements to <svg>
(it does seem to add them in the DOM explorer, but not on the screen).
One workaround is to append an <svg>
with all of the elements that you need to the page, and then modify the attributes of the elements using .attr()
.
$('body')
.append($('<svg><circle id="c" cx="10" cy="10" r="10" fill="green" /></svg>'))
.mousemove( function (e) {
$("#c").attr({
cx: e.pageX,
cy: e.pageY
});
});
For a database with high activity, you may run into issues where your updates affect actively changing records and for this reason I recommend using snapshot()
db.person.find().snapshot().forEach( function (hombre) {
hombre.name = hombre.firstName + ' ' + hombre.lastName;
db.person.save(hombre);
});
http://docs.mongodb.org/manual/reference/method/cursor.snapshot/
You can use View.clearFocus()
.
Use View.requestFocus()
called from onResume()
.
@Tim's answer only does half the work -- that gets it into a datetime.datetime object.
To get it into the string format you require, you use datetime.strftime:
print(datetime.strftime('%b %d,%Y'))
What you are trying to do can be simplified down to this.
$('input:text').bind('focus blur', function() {_x000D_
$(this).toggleClass('red');_x000D_
});
_x000D_
input{_x000D_
background:#FFFFEE;_x000D_
}_x000D_
.red{_x000D_
background-color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
<input class="calc_input" type="text" name="start_date" id="start_date" />_x000D_
<input class="calc_input" type="text" name="end_date" id="end_date" />_x000D_
<input class="calc_input" size="8" type="text" name="leap_year" id="leap_year" />_x000D_
</form>
_x000D_
By default Bootstrap does not provide grid system that allows us to create five columns layout, you need to create default column definition in the way that Bootstrap do create some custom classes and media queries in your css file
.col-xs-15,
.col-sm-15,
.col-md-15,
.col-lg-15 {
position: relative;
min-height: 1px;
padding-right: 10px;
padding-left: 10px;
}
.col-xs-15 {
width: 20%;
float: left;
}
@media (min-width: 768px) {
.col-sm-15 {
width: 20%;
float: left;
}
}
@media (min-width: 992px) {
.col-md-15 {
width: 20%;
float: left;
}
}
@media (min-width: 1200px) {
.col-lg-15 {
width: 20%;
float: left;
}
}
and some html code
<div class="row">
<div class="col-md-15 col-sm-3">
...
</div>
</div>
Simply using reflection and Groovy :
def Map toMap(object) {
return object?.properties.findAll{ (it.key != 'class') }.collectEntries {
it.value == null || it.value instanceof Serializable ? [it.key, it.value] : [it.key, toMap(it.value)]
}
}
def toObject(map, obj) {
map.each {
def field = obj.class.getDeclaredField(it.key)
if (it.value != null) {
if (field.getType().equals(it.value.class)){
obj."$it.key" = it.value
}else if (it.value instanceof Map){
def objectFieldValue = obj."$it.key"
def fieldValue = (objectFieldValue == null) ? field.getType().newInstance() : objectFieldValue
obj."$it.key" = toObject(it.value,fieldValue)
}
}
}
return obj;
}
Your arguments are in the wrong order. The connection comes first according to the docs
<?php
require("constants.php");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
error_log("Failed to connect to MySQL: " . mysqli_error($connection));
die('Internal server error');
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
error_log("Database selection failed: " . mysqli_error($connection));
die('Internal server error');
}
?>