Three flavors of my old SwissKnife library: relname_exists(anyThing)
, relname_normalized(anyThing)
and relnamechecked_to_array(anyThing)
. All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).
/**
* From my old SwissKnife Lib to your SwissKnife. License CC0.
* Check and normalize to array the free-parameter relation-name.
* Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
*/
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
SELECT array[n.nspname::text, c.relname::text]
FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
WHERE CASE
WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1] AND c.relname = x[2]
WHEN $2 IS NULL THEN n.nspname = 'public' AND c.relname = $1
ELSE n.nspname = $2 AND c.relname = $1
END
$f$ language SQL IMMUTABLE;
CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;
CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;
First use:
yarn application -list
Note down the application id Then to kill use:
yarn application -kill application_id
I use this to get the Parent, similarly for child
$( this ).children( 'li.target' ).css("border", "3px double red");
Good Luck
you can also do something more specific like that based on Anthony Artemiew's response:
<View style={globalStyles.searchSection}>
<TextInput
style={globalStyles.input}
placeholder="Rechercher"
onChangeText={(searchString) =>
{this.setState({searchString})}}
underlineColorAndroid="transparent"
/>
<Ionicons onPress={()=>console.log('Recherche en cours...')} style={globalStyles.searchIcon} name="ios-search" size={30} color="#1764A5"/>
</View>
Style:
searchSection: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
borderRadius:50,
marginLeft:35,
width:340,
height:40,
margin:25
},
searchIcon: {
padding: 10,
},
input: {
flex: 1,
paddingTop: 10,
paddingRight: 10,
paddingBottom: 10,
paddingLeft: 0,
marginLeft:10,
borderTopLeftRadius:50,
borderBottomLeftRadius:50,
backgroundColor: '#fff',
color: '#424242',
},
AndroidManifest.xml
Include launchMode="singleTop"
<activity android:name=".MessagesDetailsActivity"
android:launchMode="singleTop"
android:excludeFromRecents="true"
/>
SMSReceiver.java
Set the flags for the Intent and PendingIntent
Intent intent = new Intent(context, MessagesDetailsActivity.class);
intent.putExtra("smsMsg", smsObject.getMsg());
intent.putExtra("smsAddress", smsObject.getAddress());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
MessageDetailsActivity.java
onResume() - gets called everytime, load the extras.
Intent intent = getIntent();
String extraAddress = intent.getStringExtra("smsAddress");
String extraBody = intent.getStringExtra("smsMsg");
Hope it helps, it was based on other answers here on stackoverflow, but this is the most updated that worked for me.
<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
Password
<input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>
look into this
I hope my encoding here is right ;D To make it faster just use the ugly getInstance() call of GregorianCalendar instead of constructor call:
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class DateTest {
public static void main(final String[] args) throws Exception {
// do not forget the type cast :/
GregorianCalendar gcal = (GregorianCalendar) GregorianCalendar.getInstance();
XMLGregorianCalendar xgcal = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(gcal);
System.out.println(xgcal);
}
}
A function pointer is like any other pointer, but it points to the address of a function instead of the address of data (on heap or stack). Like any pointer, it needs to be typed correctly. Functions are defined by their return value and the types of parameters they accept. So in order to fully describe a function, you must include its return value and the type of each parameter is accepts. When you typedef such a definition, you give it a 'friendly name' which makes it easier to create and reference pointers using that definition.
So for example assume you have a function:
float doMultiplication (float num1, float num2 ) {
return num1 * num2; }
then the following typedef:
typedef float(*pt2Func)(float, float);
can be used to point to this doMulitplication
function. It is simply defining a pointer to a function which returns a float and takes two parameters, each of type float. This definition has the friendly name pt2Func
. Note that pt2Func
can point to ANY function which returns a float and takes in 2 floats.
So you can create a pointer which points to the doMultiplication function as follows:
pt2Func *myFnPtr = &doMultiplication;
and you can invoke the function using this pointer as follows:
float result = (*myFnPtr)(2.0, 5.1);
This makes good reading: http://www.newty.de/fpt/index.html
public static void ToPrintConsole(this DataTable dataTable)
{
// Print top line
Console.WriteLine(new string('-', 75));
// Print col headers
var colHeaders = dataTable.Columns.Cast<DataColumn>().Select(arg => arg.ColumnName);
foreach (String s in colHeaders)
{
Console.Write("| {0,-20}", s);
}
Console.WriteLine();
// Print line below col headers
Console.WriteLine(new string('-', 75));
// Print rows
foreach (DataRow row in dataTable.Rows)
{
foreach (Object o in row.ItemArray)
{
Console.Write("| {0,-20}", o.ToString());
}
Console.WriteLine();
}
// Print bottom line
Console.WriteLine(new string('-', 75));
}
Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:
root:~# python -V
Python 3.5.2
root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python3.5 3 auto mode
1 /usr/bin/python2.7 2 manual mode
2 /usr/bin/python3.5 3 manual mode
root:~# update-alternatives --remove python /usr/bin/python3.5
root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).
Selection Path Priority Status
------------------------------------------------------------
0 /usr/bin/python2.7 2 auto mode
* 1 /usr/bin/python2.7 2 manual mode
Press <enter> to keep the current choice[*], or type selection number: 0
root:~# python -V
Python 2.7.12
root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.
You can pass any number of arguments to the function that apply
is calling through either unnamed arguments, passed as a tuple to the args
parameter, or through other keyword arguments internally captured as a dictionary by the kwds
parameter.
For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.
s = pd.Series(np.random.randint(0,10, 10))
s
0 5
1 3
2 1
3 1
4 6
5 0
6 3
7 4
8 9
9 6
dtype: int64
s.apply(lambda x: x >= 3 and x <= 6)
0 True
1 True
2 False
3 False
4 True
5 False
6 True
7 True
8 False
9 True
dtype: bool
This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.
def between(x, low, high):
return x >= low and x =< high
We can replicate the output of the first function by passing unnamed arguments to args
:
s.apply(between, args=(3,6))
Or we can use the named arguments
s.apply(between, low=3, high=6)
Or even a combination of both
s.apply(between, args=(3,), high=6)
Something like this? Use the axisbg
keyword to subplot
:
>>> from matplotlib.figure import Figure
>>> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
>>> figure = Figure()
>>> canvas = FigureCanvas(figure)
>>> axes = figure.add_subplot(1, 1, 1, axisbg='red')
>>> axes.plot([1,2,3])
[<matplotlib.lines.Line2D object at 0x2827e50>]
>>> canvas.print_figure('red-bg.png')
(Granted, not a scatter plot, and not a black background.)
It's not what the OP asked for (capturing groups) but you can extract the numbers using:
S='This is a sample 123 text and some 987 numbers'
echo "$S" | sed 's/ /\n/g' | sed -r '/([0-9]+)/ !d'
Gives the following:
123
987
In Angular2, this can help to get components name:
getName() {
let comp:any = this.constructor;
return comp.name;
}
comp:any is needed because TypeScript compiler will issue errors since Function initially does not have property name.
Yes, but what does grouping by more two columns mean? Well, it's the same as grouping by each unique pair per row. The order you list the columns changes the way the rows are sorted.
In your example, you would write
GROUP BY fV.tier_id, f.form_template_id
Meanwhile, the code
GROUP BY f.form_template_id, fV.tier_id
would give similar results, but sorted differently.
If you're using Bootstrap 3, you can use the embed-responsive class and set the padding bottom as the height divided by the width plus a little extra for toolbars. For example, to display an 8.5 by 11 PDF, use 130% (11/8.5) plus a little extra (20%).
<div class='embed-responsive' style='padding-bottom:150%'>
<object data='URL.pdf' type='application/pdf' width='100%' height='100%'></object>
</div>
Here's the Bootstrap CSS:
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
Quassnoi's answer works, but kind of leaves you on the hook for cleaning up the dates if they are dates in the middle of the day (his start of week leaves you one day earlier than you need to be if you use a time in the middle of the day -- you can test using GETDATE()).
I've used something like this in the past:
SELECT
CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, DATECOL), DATECOL)), 101),
CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, DATECOL) - 6, DATECOL)), 101)
A side benefit of this is that by using @@DATEFIRST you can handle nonstandard week starting days (the default is Sunday, but with SET @@DATEFIRST you can change this).
It seems crazy that simple date manipulation in SQL Server has to be this arcane, but there you go...
You could follow a solution similar to "How do I force “git pull” to overwrite local files?":
git fetch --all
git reset --hard origin/abranch
git checkout $branch
That would involve only one fetch.
With Git 2.23+, git checkout
is replaced here with git switch
(presented here) (still experimental).
git switch -f $branch
(with -f
being an alias for --discard-changes
, as noted in Jan's answer)
Proceed even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
CURRENT_TIMESTAMP
is only acceptable on TIMESTAMP
fields. DATETIME
fields must be left either with a null default value, or no default value at all - default values must be a constant value, not the result of an expression.
relevant docs: http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html
You can work around this by setting a post-insert trigger on the table to fill in a "now" value on any new records.
What you are doing will not work for root user. Maybe you are running your services as root and hence you don't get to see the change.
To increase the ulimit for root user you should replace the *
by root. *
does not apply for root user. Rest is the same as you did. I will re-quote it here.
Add the following lines to the file: /etc/security/limits.conf
root soft nofile 40000
root hard nofile 40000
And then add following line in the file: /etc/pam.d/common-session
session required pam_limits.so
This will update the ulimit for root user. As mentioned in comments, you may don't even have to reboot to see the change.
The Control class has HorizontalContentAlignment and VerticalContentAlignment properties. These properties determine how a control’s content fills the space within the control.
Set HorizontalContentAlignment and VerticalContentAlignment to Center.
For completeness, in addition to the other answers, if the thread is interrupted before it blocks on Object.wait(..)
or Thread.sleep(..)
etc., this is equivalent to it being interrupted immediately upon blocking on that method, as the following example shows.
public class InterruptTest {
public static void main(String[] args) {
Thread.currentThread().interrupt();
printInterrupted(1);
Object o = new Object();
try {
synchronized (o) {
printInterrupted(2);
System.out.printf("A Time %d\n", System.currentTimeMillis());
o.wait(100);
System.out.printf("B Time %d\n", System.currentTimeMillis());
}
} catch (InterruptedException ie) {
System.out.printf("WAS interrupted\n");
}
System.out.printf("C Time %d\n", System.currentTimeMillis());
printInterrupted(3);
Thread.currentThread().interrupt();
printInterrupted(4);
try {
System.out.printf("D Time %d\n", System.currentTimeMillis());
Thread.sleep(100);
System.out.printf("E Time %d\n", System.currentTimeMillis());
} catch (InterruptedException ie) {
System.out.printf("WAS interrupted\n");
}
System.out.printf("F Time %d\n", System.currentTimeMillis());
printInterrupted(5);
try {
System.out.printf("G Time %d\n", System.currentTimeMillis());
Thread.sleep(100);
System.out.printf("H Time %d\n", System.currentTimeMillis());
} catch (InterruptedException ie) {
System.out.printf("WAS interrupted\n");
}
System.out.printf("I Time %d\n", System.currentTimeMillis());
}
static void printInterrupted(int n) {
System.out.printf("(%d) Am I interrupted? %s\n", n,
Thread.currentThread().isInterrupted() ? "Yes" : "No");
}
}
Output:
$ javac InterruptTest.java
$ java -classpath "." InterruptTest
(1) Am I interrupted? Yes
(2) Am I interrupted? Yes
A Time 1399207408543
WAS interrupted
C Time 1399207408543
(3) Am I interrupted? No
(4) Am I interrupted? Yes
D Time 1399207408544
WAS interrupted
F Time 1399207408544
(5) Am I interrupted? No
G Time 1399207408545
H Time 1399207408668
I Time 1399207408669
Implication: if you loop like the following, and the interrupt occurs at the exact moment when control has left Thread.sleep(..)
and is going around the loop, the exception is still going to occur. So it is perfectly safe to rely on the InterruptedException being reliably thrown after the thread has been interrupted:
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException ie) {
break;
}
}
I had the same problem and just solved it. I had posted my own question on stackoverflow:
Can't PUT to my IHttpHandler, GET works fine
The solution was to set runManagedModulesForWebDavRequests to true in the modules element. My guess is that once you install WebDAV then all PUT requests are associated with it. If you need the PUT to go to your handler, you need to remove the WebDAV module and set this attribute to true.
<modules runManagedModulesForWebDavRequests="true">
...
</modules>
So if you're running into the problem when you use the PUT verb and you have installed WebDAV then hopefully this solution will fix your problem.
The error you're getting is that self.adj
doesn't already have a key 0
. You're trying to append to a list that doesn't exist yet.
Consider using a defaultdict
instead, replacing this line (in __init__
):
self.adj = {}
with this:
self.adj = defaultdict(list)
You'll need to import at the top:
from collections import defaultdict
Now rather than raise a KeyError
, self.adj[0].append(edge)
will create a list automatically to append to.
The way I handled this was switching the className of a label based on a condition. This way you only need one label and you can have different classes for different states... Hope that helps!
try this solution for me its working
public List<ProjectInfo> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext
(DBHelper.GetConnectionString()))
{
return (from pro in db.Projects
select new { query }.query).ToList();
}
}
Really the format can be quite simple - sometimes there's no need to predefine a temp table - it will be created from results of the select.
Select FieldA...FieldN
into #MyTempTable
from MyTable
So unless you want different types or are very strict on definition, keep things simple. Note also that any temporary table created inside a stored procedure is automatically dropped when the stored procedure finishes executing. If stored procedure A creates a temp table and calls stored procedure B, then B will be able to use the temporary table that A created.
However, it's generally considered good coding practice to explicitly drop every temporary table you create anyway.
Looks like Windows might just let you do this...
Unfortunately I don't think you're going to get around starting a separate process unless you go to a third party component.
If you want to print/write double value at console then use System.out.printf()
or System.out.format()
methods.
System.out.printf("\n$%10.2f",shippingCost);
System.out.printf("%n$%.2f",shippingCost);
Presenting an alternative way of solving this. This may be better or worse than Dan's solution, depending on your application.
You can get the state from the reducers into the actions by splitting the action in 2 separate functions: first ask for the data, second act on the data. You can do that by using redux-loop
.
First 'kindly ask for the data'
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
}
}
In the reducer, intercept the ask and provide the data to the second stage action by using redux-loop
.
import { loop, Cmd } from 'redux-loop';
const initialState = { data: '' }
export default (state=initialState, action) => {
switch(action.type) {
case SOME_ACTION: {
return loop(state, Cmd.action(anotherAction(state.data))
}
}
}
With the data in hand, do whatever you initially wanted
export const ANOTHER_ACTION = 'ANOTHER_ACTION';
export function anotherAction(data) {
return {
type: ANOTHER_ACTION,
payload: data,
}
}
Hope this helps someone.
A lambda function is an anonymous function that you create in-line. It can capture variables as some have explained, (e.g. http://www.stroustrup.com/C++11FAQ.html#lambda) but there are some limitations. For example, if there's a callback interface like this,
void apply(void (*f)(int)) {
f(10);
f(20);
f(30);
}
you can write a function on the spot to use it like the one passed to apply below:
int col=0;
void output() {
apply([](int data) {
cout << data << ((++col % 10) ? ' ' : '\n');
});
}
But you can't do this:
void output(int n) {
int col=0;
apply([&col,n](int data) {
cout << data << ((++col % 10) ? ' ' : '\n');
});
}
because of limitations in the C++11 standard. If you want to use captures, you have to rely on the library and
#include <functional>
(or some other STL library like algorithm to get it indirectly) and then work with std::function instead of passing normal functions as parameters like this:
#include <functional>
void apply(std::function<void(int)> f) {
f(10);
f(20);
f(30);
}
void output(int width) {
int col;
apply([width,&col](int data) {
cout << data << ((++col % width) ? ' ' : '\n');
});
}
A tweak of Daniel's version to calculate percentile along with rank. Also two people with same marks will get the same rank.
set @totalStudents = 0;
select count(*) into @totalStudents from marksheets;
SELECT id, score, @curRank := IF(@prevVal=score, @curRank, @studentNumber) AS rank,
@percentile := IF(@prevVal=score, @percentile, (@totalStudents - @studentNumber + 1)/(@totalStudents)*100),
@studentNumber := @studentNumber + 1 as studentNumber,
@prevVal:=score
FROM marksheets, (
SELECT @curRank :=0, @prevVal:=null, @studentNumber:=1, @percentile:=100
) r
ORDER BY score DESC
Results of the query for a sample data -
+----+-------+------+---------------+---------------+-----------------+
| id | score | rank | percentile | studentNumber | @prevVal:=score |
+----+-------+------+---------------+---------------+-----------------+
| 10 | 98 | 1 | 100.000000000 | 2 | 98 |
| 5 | 95 | 2 | 90.000000000 | 3 | 95 |
| 6 | 91 | 3 | 80.000000000 | 4 | 91 |
| 2 | 91 | 3 | 80.000000000 | 5 | 91 |
| 8 | 90 | 5 | 60.000000000 | 6 | 90 |
| 1 | 90 | 5 | 60.000000000 | 7 | 90 |
| 9 | 84 | 7 | 40.000000000 | 8 | 84 |
| 3 | 83 | 8 | 30.000000000 | 9 | 83 |
| 4 | 72 | 9 | 20.000000000 | 10 | 72 |
| 7 | 60 | 10 | 10.000000000 | 11 | 60 |
+----+-------+------+---------------+---------------+-----------------+
quick answer is this:
sh "ls -l > commandResult"
result = readFile('commandResult').trim()
I think there exist a feature request to be able to get the result of sh step, but as far as I know, currently there is no other option.
EDIT: JENKINS-26133
EDIT2: Not quite sure since what version, but sh/bat steps now can return the std output, simply:
def output = sh returnStdout: true, script: 'ls -l'
VSCode comes with in-built color themes which can be used to change the colors of the editor and the terminal.
ctrl+k+t
in windows/ubuntu or cmd+k+t
on mac.ctrl+shift+p
in windows/ubuntu or cmd+shift+p
on mac and type color
. Select preferences: color theme
from the options, to select your favourite color.category:themes
to install your favourite themes. (If you need to sort the themes by installs search category:themes @sort:installs
)Edit - for manually editing colors in terminal
VSCode team have removed customizing colors from user settings page. Currently using the themes is the only way to customize terminal colors in VSCode. For more information check out issue #6766
In Swift, using xcode 7 (and later), you can add the following to your AppDelegate.swift file:
UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
This is the what the complete method looks like:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// I added this line
UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
return true
}
In the example above my item will be white. The "/255.0" is needed because it expects a value from 0 to 1. For white, I could have just used 1. But for other color you'll probably be using RGB values.
CSS3 has the overflow-x
property, but I wouldn't expect great support for that. In CSS2 all you can do is set a general scroll
policy and work your widths
and heights
not to mess them up.
Another way:
a xls(x) file is just a collection of *.xml files stored in a *.zip container. unzip the file "app.xml" in the folder docProps.
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<Properties xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes" xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">
<TotalTime>0</TotalTime>
<Application>Microsoft Excel</Application>
<DocSecurity>0</DocSecurity>
<ScaleCrop>false</ScaleCrop>
-<HeadingPairs>
-<vt:vector baseType="variant" size="2">
-<vt:variant>
<vt:lpstr>Arbeitsblätter</vt:lpstr>
</vt:variant>
-<vt:variant>
<vt:i4>4</vt:i4>
</vt:variant>
</vt:vector>
</HeadingPairs>
-<TitlesOfParts>
-<vt:vector baseType="lpstr" size="4">
<vt:lpstr>Tabelle3</vt:lpstr>
<vt:lpstr>Tabelle4</vt:lpstr>
<vt:lpstr>Tabelle1</vt:lpstr>
<vt:lpstr>Tabelle2</vt:lpstr>
</vt:vector>
</TitlesOfParts>
<Company/>
<LinksUpToDate>false</LinksUpToDate>
<SharedDoc>false</SharedDoc>
<HyperlinksChanged>false</HyperlinksChanged>
<AppVersion>14.0300</AppVersion>
</Properties>
The file is a german file (Arbeitsblätter = worksheets). The table names (Tabelle3 etc) are in the correct order. You just need to read these tags;)
regards
From the first answer,
"Using Mongoose, a user can define the schema for the documents in a particular collection. It provides a lot of convenience in the creation and management of data in MongoDB."
You can now also define schema with mongoDB native driver using
##For new collection
`db.createCollection("recipes",
validator: { $jsonSchema: {
<<Validation Rules>>
}
}
)`
##For existing collection
`db.runCommand( {
collMod: "recipes",
validator: { $jsonSchema: {
<<Validation Rules>>
}
}
} )`
##full example
`db.createCollection("recipes", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "servings", "ingredients"],
additionalProperties: false,
properties: {
_id: {},
name: {
bsonType: "string",
description: "'name' is required and is a string"
},
servings: {
bsonType: ["int", "double"],
minimum: 0,
description:
"'servings' is required and must be an integer with a minimum of zero."
},
cooking_method: {
enum: [
"broil",
"grill",
"roast",
"bake",
"saute",
"pan-fry",
"deep-fry",
"poach",
"simmer",
"boil",
"steam",
"braise",
"stew"
],
description:
"'cooking_method' is optional but, if used, must be one of the listed options."
},
ingredients: {
bsonType: ["array"],
minItems: 1,
maxItems: 50,
items: {
bsonType: ["object"],
required: ["quantity", "measure", "ingredient"],
additionalProperties: false,
description: "'ingredients' must contain the stated fields.",
properties: {
quantity: {
bsonType: ["int", "double", "decimal"],
description:
"'quantity' is required and is of double or decimal type"
},
measure: {
enum: ["tsp", "Tbsp", "cup", "ounce", "pound", "each"],
description:
"'measure' is required and can only be one of the given enum values"
},
ingredient: {
bsonType: "string",
description: "'ingredient' is required and is a string"
},
format: {
bsonType: "string",
description:
"'format' is an optional field of type string, e.g. chopped or diced"
}
}
}
}
}
}
}
});`
Insert collection Example
`db.recipes.insertOne({
name: "Chocolate Sponge Cake Filling",
servings: 4,
ingredients: [
{
quantity: 7,
measure: "ounce",
ingredient: "bittersweet chocolate",
format: "chopped"
},
{ quantity: 2, measure: "cup", ingredient: "heavy cream" }
]
});`
use the include is the easiest way as per
http://www.vistax64.com/powershell/168315-get-childitem-filter-files-multiple-extensions.html
In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.
I solved this issue by setting the Copy Local attribute of my project's references to true.
This question was asked in 2012 before flexbox. The correct way to solve this problem using modern CSS is with a media query and a flex column reversal for mobile devices. No absolute positioning is needed.
https://jsfiddle.net/tnhsaesop/vjftq198/3/
HTML:
<div class="parent">
<div style="background-color:lightgrey;">
<p>
I stay on top on desktop and I'm on bottom on mobile
</p>
</div>
<div style="background-color:grey;">
<p>
I stay on bottom on desktop and I'm on top on mobile
</p>
</div>
</div>
CSS:
.parent {
display: flex;
flex-direction: column;
}
@media (max-width: 768px) {
.parent {
flex-direction: column-reverse;
}
}
The followin example shows how to capture and process video frames in HTML5:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Capturing & Processing Video in HTML5</title>
</head>
<body>
<div>
<h2>Camera Preview</h2>
<video id="cameraPreview" width="240" height="180" autoplay></video>
<p>
<button id="startButton" onclick="startCapture();">Start Capture</button>
<button id="stopButton" onclick="stopCapture();">Stop Capture</button>
</p>
</div>
<div>
<h2>Processing Preview</h2>
<canvas id="processingPreview" width="240" height="180"></canvas>
</div>
<div>
<h2>Recording Preview</h2>
<video id="recordingPreview" width="240" height="180" autoplay controls></video>
<p>
<a id="downloadButton">Download</a>
</p>
</div>
<script>
const ROI_X = 250;
const ROI_Y = 150;
const ROI_WIDTH = 240;
const ROI_HEIGHT = 180;
const FPS = 25;
let cameraStream = null;
let processingStream = null;
let mediaRecorder = null;
let mediaChunks = null;
let processingPreviewIntervalId = null;
function processFrame() {
let cameraPreview = document.getElementById("cameraPreview");
processingPreview
.getContext('2d')
.drawImage(cameraPreview, ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT, 0, 0, ROI_WIDTH, ROI_HEIGHT);
}
function generateRecordingPreview() {
let mediaBlob = new Blob(mediaChunks, { type: "video/webm" });
let mediaBlobUrl = URL.createObjectURL(mediaBlob);
let recordingPreview = document.getElementById("recordingPreview");
recordingPreview.src = mediaBlobUrl;
let downloadButton = document.getElementById("downloadButton");
downloadButton.href = mediaBlobUrl;
downloadButton.download = "RecordedVideo.webm";
}
function startCapture() {
const constraints = { video: true, audio: false };
navigator.mediaDevices.getUserMedia(constraints)
.then((stream) => {
cameraStream = stream;
let processingPreview = document.getElementById("processingPreview");
processingStream = processingPreview.captureStream(FPS);
mediaRecorder = new MediaRecorder(processingStream);
mediaChunks = []
mediaRecorder.ondataavailable = function(event) {
mediaChunks.push(event.data);
if(mediaRecorder.state == "inactive") {
generateRecordingPreview();
}
};
mediaRecorder.start();
let cameraPreview = document.getElementById("cameraPreview");
cameraPreview.srcObject = stream;
processingPreviewIntervalId = setInterval(processFrame, 1000 / FPS);
})
.catch((err) => {
alert("No media device found!");
});
};
function stopCapture() {
if(cameraStream != null) {
cameraStream.getTracks().forEach(function(track) {
track.stop();
});
}
if(processingStream != null) {
processingStream.getTracks().forEach(function(track) {
track.stop();
});
}
if(mediaRecorder != null) {
if(mediaRecorder.state == "recording") {
mediaRecorder.stop();
}
}
if(processingPreviewIntervalId != null) {
clearInterval(processingPreviewIntervalId);
processingPreviewIntervalId = null;
}
};
</script>
</body>
</html>
_x000D_
Thanks for John Doe's solution that helped a lot. Mine is very similar with some difference, using TempVars
Instead of :
strSQL = "SELECT * FROM Table1 WHERE Name = Forms!Table!Control;"
I used:
strSQL = "SELECT * FROM Query1" , Query1 being common for other usage
Query1 as:
"Select Field1, Field2 from Table1 where Id= [TempVars]![MyVar]
And similarly, removing [TempVars]![MyVar]
from view solved the problem.
trying to install global packages into C:\Program Files (x86)\nodejs\
gave me Run as Administrator issues, because npm was trying to install into
C:\Program Files (x86)\nodejs\node_modules\
to resolve this, change global install directory to C:\Users\{username}\AppData\Roaming\npm
:
in C:\Users\{username}\
, create .npmrc
file with contents:
prefix = "C:\\Users\\{username}\\AppData\\Roaming\\npm"
reference
npm install -g package
installs global packages into prefix locationnpm config ls -l
was showing prefix = "C:\\Program Files (x86)\\nodejs"
environment
nodejs x86 installer into C:\Program Files (x86)\nodejs\
on Windows 7 Ultimate N 64-bit SP1
node --version
: v0.10.28
npm --version
: 1.4.10
I was able to stop via this on Windows for Angular 8:
Step 1: Find 4200 process
netstat -ano | findstr :4200
Step 2: Kill that process:
taskkill /PID <PID> /F
On button click you can try the following.
protected void button1_Click(object sender, EventArgs e)
{
Response.Redirect("~/Admin/Admin.aspx");
}
And on PageLoad you can check whether the loading is coming from that button then increase the count.
protected void Page_Load(object sender, EventArgs e)
{
StackTrace stackTrace = new StackTrace();
string eventName = stackTrace.GetFrame(1).GetMethod().Name; // this will the event name.
if (eventName == "button1_Click")
{
// code to increase the count;
}
}
Thanks
Here is a simple thumb-rule that I use help me decide as when to use flatMap()
over map()
in Rx's Observable
.
Once you come to a decision that you're going to employ a map
transformation, you'd write your transformation code to return some Object right?
If what you're returning as end result of your transformation is:
a non-observable object then you'd use just map()
. And map()
wraps that object in an Observable and emits it.
an Observable
object, then you'd use flatMap()
. And flatMap()
unwraps the Observable, picks the returned object, wraps it with its own Observable and emits it.
Say for example we've a method titleCase(String inputParam) that returns Titled Cased String object of the input param. The return type of this method can be String
or Observable<String>
.
If the return type of titleCase(..)
were to be mere String
, then you'd use map(s -> titleCase(s))
If the return type of titleCase(..)
were to be Observable<String>
, then you'd use flatMap(s -> titleCase(s))
Hope that clarifies.
In case this is an option for you, if you put your data into object form it works the way I think you're hoping for:
$scope.steps = {
companyName: true,
businessType: true,
physicalAddress: true
};
Here's a fiddle of this: http://jsfiddle.net/zMjVp/
In ES8 using moment, now and start being moment objects.
const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
Are you just dealing with ASCII strings, and have no locale issues? Then yes, that would be a good way to do it.
You're in the less
program, which makes the output of git log
scrollable.
Type q to exit this screen. Type h to get help.
If you don't want to read the output in a pager and want it to be just printed to the terminal define the environment variable GIT_PAGER
to cat
or set core.pager
to cat
(execute git config --global core.pager cat
).
Have you tried with the custom format "#,##0.##"
?
If its javascript that runs on a button click, then making the change under Sources>Sources (in the developer tools in chrome ) and pressing Ctrl +S to save, is enough. I do this all the time.
If you refresh the page, your javascript changes would be gone, but chrome will still remember your break points.
One solution is to use also the first image as a background image like this:
<div id="Library"></div>
#Library {
background-image: url('LibraryTransparent.png');
height: 70px;
width: 120px;
}
#Library:hover {
background-image: url('LibraryHoverTrans.png');
}
If your hover image has a different size, you've got to set them like so:
#Library:hover {
background-image: url('LibraryHoverTrans.png');
width: [IMAGE_WIDTH_IN_PIXELS]px;
height: [IMAGE_HEIGHT_IN_PIXELS]px;
}
Try
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]
As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.
The problem with both iDevlop's and Ashok's answers is that the fundamental problem is an Excel design flaw (apparently) in which the Open method fails to respect the Application.ScreenUpdating setting of False. Consequently, setting it to False is of no benefit to this problem.
If Patrick McDonald's solution is too burdensome due to the overhead of starting a second instance of Excel, then the best solution I've found is to minimize the time that the opened workbook is visible by re-activating the original window as quickly as possible:
Dim TempWkBk As Workbook
Dim CurrentWin As Window
Set CurrentWin = ActiveWindow
Set TempWkBk = Workbooks.Open(SomeFilePath)
CurrentWin.Activate 'Allows only a VERY brief flash of the opened workbook
TempWkBk.Windows(1).Visible = False 'Only necessary if you also need to prevent
'the user from manually accessing the opened
'workbook before it is closed.
'Operate on the new workbook, which is not visible to the user, then close it...
Standard interpolate + linear extrapolate:
def interpola(v, x, y):
if v <= x[0]:
return y[0]+(y[1]-y[0])/(x[1]-x[0])*(v-x[0])
elif v >= x[-1]:
return y[-2]+(y[-1]-y[-2])/(x[-1]-x[-2])*(v-x[-2])
else:
f = interp1d(x, y, kind='cubic')
return f(v)
'Greedy' means match longest possible string.
'Lazy' means match shortest possible string.
For example, the greedy h.+l
matches 'hell'
in 'hello'
but the lazy h.+?l
matches 'hel'
.
I have that kind of spring setup working
an abstract class with an autowired field
public abstract class AbstractJobRoute extends RouteBuilder {
@Autowired
private GlobalSettingsService settingsService;
and several children defined with @Component
annotation.
I think following command may help you!
mvn -U clean install
Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):
erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"
erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"
erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"
erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"
@rem Clear IE cache - (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"
@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"
@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"
pause
I am pretty sure it will run for some time when you first run it :) Enjoy!
Yess, possible with conditions:
If you have your app installed in the user phone and a server app communicating with this app, and there at last one of location service providers activated in the user phone, and some horrible android permissions!
In most of android phones there 3 location providers that can give exact location (GPS_PROVIDER 1m) or estimated (NETWORK_PROVIDER around 2-20m) and PASSIVE_PROVIDER (more in LocationManager official documentation).
1* App sends SMS to user's phone
Yess, can be server app or you create an android app if you want something automated, so you can do it manually by sending SMS from your default SMS app! I use Kannel: Open Source WAP and SMS Gateway and here (lot of APIs to send SMS )
2* App receives SMS at user's phone from the SMS sender
Yess, you can get all received SMS, and you can filter them by sender phone number! and do some actions when your specified sms received, basic tuto here (i do some actions according to the content of my SMS)
3* App gets location coordinates of the user's phone
Yess, you can get actual user coordinates easily if one of location providers is activated, so you can get last known location when the user have activated one of location providers, if those disabled or the phone don't have GPS hardware you can use Open Cell Id api to get the nearest cell coordinates(10m-10Km) or Loc8 api but those not available in all around the world, and some apps use IP location apis to get the country, city and province, here the simplest way to get current user location.
4* App sends location coordinates to the SMS sender via SMS
Yess, you can get sender phone number and send user location, immediately when SMS received or at specified times in the day.
(Those 4 yesses for you :) )
Viber and other apps that access to users locations, identify there users by there phone numbers by obligating them to send SMS to the server app to create an account and activate the free service (Ex:VOIP) , and lunch a service that can:
And your application users must accept all of that when installing it, of corse i don't gonna install apps like this because i read permissions before installing :) and permissions maybe something like that:
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<-- and more if you wanna more -->
The final user will accept for something like that (those permissions of an android app u asked about):
This app has access to these permissions:
Your accounts -create accounts and set passwords -find accounts on the device -add or remove accounts -use accounts on the device -read Google service configuration
Your location -approximate location (network-based) -precise location (GPS and network-based)
Your messages -receive text messages (SMS) -send SMS messages -edit your text messages (SMS or MMS) -read your text messages (SMS or MMS)
Network communication -receive data from Internet -full network access -view Wi-Fi connections -view network connections -change network connectivity
Phone calls -read phone status and identity -directly call phone numbers
Storage -modify or delete the contents of your USB storage
Your applications information -retrieve running apps -close other apps -run at startup
Bluetooth -pair with Bluetooth devices -access Bluetooth settings
Camera -take pictures and videos
Other Application UI -draw over other apps
Microphone -record audio
Lock screen -disable your screen lock
Your social information -read your contacts -modify your contacts -read call log -write call log -read your social stream -write to your social stream
Development tools -read sensitive log data
System tools -modify system settings -send sticky broadcast -test access to protected storage
Affects battery -control vibration -prevent device from sleeping
Audio settings -change your audio settings
Sync Settings -read sync settings -toggle sync on and off -read sync statistics
Wallpaper -set wallpaper
You don't need to use
adb shell getevent -l
command, you just need to enable in Developer Options on the device [Show Touch data] to get X and Y.
Some more information can be found in my article here: https://mobileqablog.wordpress.com/2016/08/20/android-automatic-touchscreen-taps-adb-shell-input-touchscreen-tap/
Mike, I had the same problem with SSIS in SQL Server 2005... Apparently, the DataFlowDestination object will always attempt to validate the data coming in, into Unicode. Go to that object, Advanced Editor, Component Properties pane, change the "ValidateExternalMetaData" property to False. Now, go to the Input and Output Properties pane, Destination Input, External Columns - set each column Data type and Length to match the database table it's going to. Now, when you close that editor, those column changes will be saved and not validated over, and it will work.
You mean like this?
> eq = function(x){x*x}
> plot(eq(1:1000), type='l')
(Or whatever range of values is relevant to your function)
You can just do it like this:
#content {
position: relative;
}
#content img {
position: absolute;
top: 0px;
right: 0px;
}
<div id="content">
<img src="images/ribbon.png" class="ribbon"/>
<div>some text...</div>
</div>
REM setting current_schema is required as the 2nd query depends on the current user referred in the session
ALTER SESSION SET CURRENT_SCHEMA=TABLE_OWNER;
SELECT table_name,
TO_NUMBER (
EXTRACTVALUE (
xmltype (
DBMS_XMLGEN.getxml ('select count(*) c from ' || table_name)),
'/ROWSET/ROW/C'))
COUNT
FROM dba_tables
WHERE owner = 'TABLE_OWNER'
ORDER BY COUNT DESC;
conda activate myEnv
conda list --explicit > myEnvBkp.txt
conda create --name myEnvRestored --file myEnvBkp.txt
Stashing, temporary commits and rebasing may all be overkill. If you haven't added the changed files to the index, yet, then you may be able to just checkout the other branch.
git checkout branch2
This will work so long as no files that you are editing are different between branch1 and branch2. It will leave you on branch2 with you working changes preserved. If they are different then you can specify that you want to merge your local changes with the changes introduced by switching branches with the -m
option to checkout.
git checkout -m branch2
If you've added changes to the index then you'll want to undo these changes with a reset first. (This will preserve your working copy, it will just remove the staged changes.)
git reset
Given MyObject
that has a DateTime
member with a getDateTime()
method, you can sort an ArrayList
that contains MyObject
elements by the DateTime
objects like this:
Collections.sort(myList, new Comparator<MyObject>() {
public int compare(MyObject o1, MyObject o2) {
return o1.getDateTime().lt(o2.getDateTime()) ? -1 : 1;
}
});
Regular grammar is either right or left linear, whereas context free grammar is basically any combination of terminals and non-terminals. Hence you can see that regular grammar is a subset of context-free grammar.
So for a palindrome for instance, is of the form,
S->ABA
A->something
B->something
You can clearly see that palindromes cannot be expressed in regular grammar since it needs to be either right or left linear and as such cannot have a non-terminal on both side.
Since regular grammars are non-ambiguous, there is only one production rule for a given non-terminal, whereas there can be more than one in the case of a context-free grammar.
I tried running on Windows, and got this problem after an update. I tried restarting the docker service as well as my pc, but nothing worked.
When running:
curl https://registry-1.docker.io/v2/ && echo Works
I got back:
{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":null}]}
Works
Eventually, I tried: https://github.com/moby/moby/issues/22635#issuecomment-284956961
By changing the fixed address to 8.8.8.8:
Which worked for me!
I still got the unauthorized message for curl https://registry-1.docker.io/v2/
but I managed to pull images from docker hub.
MAC OS
Check status
brew services list
Something like:
Name Status User Plist
mongodb stopped
start it
brew services start mongodb
Try it again
mongo
or mongo --port 27017
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
Did you mean the executable fails to run , if invoked from any other directory? This is rather a bug on the executable. One potential reason could be the executable requires some shared libraires from the installed folder. You may check environment variable LD_LIBRARY_PATH
public class UserInfo {
String LoginId;
String Password;
String FirstName;
String LastName;
String Email;
String Mobile;
String Address;
String DOB;
public String getLoginId() {
return LoginId;
}
public void setLoginId(String loginId) {
LoginId = loginId;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getMobile() {
return Mobile;
}
public void setMobile(String mobile) {
Mobile = mobile;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getDOB() {
return DOB;
}
public void setDOB(String DOB) {
this.DOB = DOB;
}
}
It probably makes sense to emphasize one thing that the most have missed, which may prevent immediate understanding. When you type python
in terminal you don't normally provide a full path. Instead, the executable is up looked in PATH
environment variable. In turn, when you want to execute a Python program directly, /path/to/app.py
, one must tell the shell what interpreter to use (via the hashbang, what the other contributors are explaining above).
Hashbang expects full path to an interpreter. Thus to run your Python program directly you have to provide full path to Python binary which varies significantly, especially considering a use of virtualenv. To address portability the trick with /usr/bin/env
is used. The latter is originally intended to alter environment in-place and run a command in it. When no alteration is provided it runs the command in current environment, which effectively results in the same PATH
lookup which does the trick.
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
PHP 7.X Centos 7
I got dependency issues when trying to install module with above suggestions, adding this flag:
--enablerepo=remi-php7X
Resolved dependencies.
So
sudo yum --enablerepo=remi-php7X install php-xml
Then
service httpd restart
Ref: Install PHP Modules
I'll give a slightly advanced answer. In Python, functions are first-class objects. This means they can be "dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have."
Calling a function/class instance in Python means invoking the __call__
method of that object. For old-style classes, class instances are also callable but only if the object which creates them has a __call__
method. The same applies for new-style classes, except there is no notion of "instance" with new-style classes. Rather they are "types" and "objects".
As quoted from the Python 2 Data Model page, for function objects, class instances(old style classes), and class objects(new-style classes), "x(arg1, arg2, ...)
is a shorthand for x.__call__(arg1, arg2, ...)
".
Thus whenever you define a function with the shorthand def funcname(parameters):
you are really just creating an object with a method __call__
and the shorthand for __call__
is to just name the instance and follow it with parentheses containing the arguments to the call. Because functions are first class objects in Python, they can be created on the fly with dynamic parameters (and thus accept dynamic arguments). This comes into handy with decorator functions/classes which you will read about later.
For now I suggest reading the Official Python Tutorial.
{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}
console.dir()
will do what you need. It will give you a hierarchical structure of the data.
success:function(data){
console.dir(data);
}
like so
> Object
> input_data: Object
price-row_122: " 35.1 "
quantity-row_122: "1"
success: true
I don't think you need console.log(JSON.stringify(data))
.
To get the data you can do this without stringify
:
console.log(data.success); // true
console.log(data.input_data['quantity-row_122']) // "1"
console.log(data.input_data['price-row_122']) // " 35.1 "
Note
The value from input_data
Object will be typeof "1"
: String
, but you can convert to number(Int or Float)
using ParseInt or ParseFloat, like so:
typeof parseFloat(data.input_data['price-row_122'], 10) // "number"
parseFloat(data.input_data['price-row_122'], 10) // 35.1
A key issue here is that this loop iterates over the rows (1st dimension) of B
:
In [258]: B
Out[258]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [259]: for b in B:
...: print(b,'=>',end='')
...: b += 1
...: print(b)
...:
[0 1 2] =>[1 2 3]
[3 4 5] =>[4 5 6]
[6 7 8] =>[7 8 9]
[ 9 10 11] =>[10 11 12]
Thus the +=
is acting on a mutable object, an array.
This is implied in the other answers, but easily missed if your focus is on the a = a+1
reassignment.
I could also make an in-place change to b
with [:]
indexing, or even something fancier, b[1:]=0
:
In [260]: for b in B:
...: print(b,'=>',end='')
...: b[:] = b * 2
[1 2 3] =>[2 4 6]
[4 5 6] =>[ 8 10 12]
[7 8 9] =>[14 16 18]
[10 11 12] =>[20 22 24]
Of course with a 2d array like B
we usually don't need to iterate on the rows. Many operations that work on a single of B
also work on the whole thing. B += 1
, B[1:] = 0
, etc.
1.question answer-In your mobile having Developer Option in settings and enable that one. after In android studio project source file in bin--> apk file .just copy the apk file and paste in mobile memory in ur pc.. after all finished .you click that apk file in your mobile is automatically installed.
2.question answer-Your mobile is Samsung are just add Samsung Kies software in your pc..its helps to android code run in your mobile ...
actually, your answer is not complete as the values also depend on the wrapping container. In case of relative or linear layouts, the values behave like this:
In case of an horizontal scroll view, your code will work.
The most efficient way is to take input make the logic and run
so the code is like this to make your own space maker
need = input("Write a string:- ")
result = ''
for character in need:
result = result + character + ' '
print(result) # to rid of space after O
but if you want to use what python give then use this code
need2 = input("Write a string:- ")
print(" ".join(need2))
Ok folks, I ran into this problem this weekend when my OpenStack environment crashed. Another post about that coming soon on how to recover.
I found a solution that worked for me with a SQL Server instance running under the Ver 15.1 Distrib 10.1.21-MariaDB with Fedora 25 Server as the host. Do not listen to all the other posts that say your database is corrupted if you completely copied your old mariadb-server's /var/lib/mysql directory and the database you are copying is not already corrupted. This process is based on a system where the OS became corrupted but its files were still accessible.
Here are the steps I followed.
Make sure that you have completely uninstalled any current versions of SQL only on the NEW server. Also, make sure ALL mysql-server or mariadb-server processes on the NEW AND OLD servers have been halted by running:
service mysqld stop or service mariadb stop.
On the NEW SQL server go into the /var/lib/mysql directory and ensure that there are no files at all in this directory. If there are files in this directory then your process for removing the database server from the new machine did not work and is possibly corrupted. Make sure it completely uninstalled from the new machine.
On the OLD SQL server:
mkdir /OLDMYSQL-DIR cd /OLDMYSQL-DIR tar cvf mysql-olddirectory.tar /var/lib/mysql gzip mysql-olddirectory.tar
Make sure you have sshd running on both the OLD and NEW servers. Make sure there is network connectivity between the two servers.
On the NEW SQL server:
mkdir /NEWMYSQL-DIR
On the OLD SQL server:
cd /OLDMYSQL-DIR scp mysql-olddirectory.tar.gz @:/NEWMYSQL-DIR
On the NEW SQL server:
cd /NEWMYSQL-DIR gunzip mysql-olddirectory.tar.gz OR tar zxvf mysql-olddirectory.tar.gz (if tar zxvf doesn't work) tar xvf mysql-olddirectory.tar.gz
You should now have a "mysql" directory file sitting in the NEWMYSQL-DIR. Resist the urge to run a "cp" command alone with no switches. It will not work. Run the following "cp" command and ensure you use the same switches I did.
cd mysql/ cp -rfp * /var/lib/mysql/
Now you should have a copy of all of your old SQL server files on the NEW server with permissions in tact. On the NEW SQL server:
cd /var/lib/mysql/
VERY IMPORTANT STEP. DO NOT SKIP
> rm -rfp ib_logfile*
FOR MARIADB-SERVER and DNF:
> dnf install mariadb-server
> service mariadb restart
FOR MYSQL-SERVER and YUM:
> yum install mysql-server
> service mysqld restart
If you have an array such as
var people = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" }
];
You can use the filter
method of an Array object:
people.filter(function (person) { return person.dinner == "sushi" });
// => [{ "name": "john", "dinner": "sushi" }]
In newer JavaScript implementations you can use a function expression:
people.filter(p => p.dinner == "sushi")
// => [{ "name": "john", "dinner": "sushi" }]
You can search for people who have "dinner": "sushi"
using a map
people.map(function (person) {
if (person.dinner == "sushi") {
return person
} else {
return null
}
}); // => [null, { "name": "john", "dinner": "sushi" }, null]
or a reduce
people.reduce(function (sushiPeople, person) {
if (person.dinner == "sushi") {
return sushiPeople.concat(person);
} else {
return sushiPeople
}
}, []); // => [{ "name": "john", "dinner": "sushi" }]
I'm sure you are able to generalize this to arbitrary keys and values!
You can add "issue time" to token and maintain "last logout time" for each user on the server. When you check token validity, also check "issue time" be after "last logout time".
For selecting all in visual: Type Esc to be sure yor are in normal mode
:0
type ENTER to go to the beginning of file
vG
You can either use the answer from the duplicate link pointed by nvm.
Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):
git pull -s recursive -X theirs
Text will never wrap to the next line. The text continues on the same line until a
tag is encountered.
.dropdown-menu {
white-space: nowrap;
}
It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src
and the package file under $GOPATH/pkg/<architecture>
, for example: $GOPATH/pkg/windows_amd64
.
In Linux: remove the directory ~/.android
and restart ADB.
Very easy no need create class extends LocationListener 1- Variable
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;
2- onStartService()
@Override public void onStartService() {
addListenerLocation();
}
3- Method addListenerLocation()
private void addListenerLocation() {
mLocationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
currentLat = location.getLatitude();
currentLon = location.getLongitude();
Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(lastKnownLocation!=null){
currentLat = lastKnownLocation.getLatitude();
currentLon = lastKnownLocation.getLongitude();
}
}
@Override
public void onProviderDisabled(String provider) {
}
};
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}
4- onDestroy()
@Override
public void onDestroy() {
super.onDestroy();
mLocationManager.removeUpdates(mLocationListener);
}
In case somebody has this problem
Cannot invoke initializer for type 'Int' with an argument list of type '(Array<Element>.Index?)'
jsut do this
extension Int {
var toInt: Int {
return self
}
}
then
guard let finalIndex = index?.toInt else {
return false
}
The easiest option is to make use of the Excel copy/paste.
Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub
The way to get the results of your formula would be to start in a new sheet.
In cell A1 put the formula
=IF('testsheet'!C1 <= 99,'testsheet'!A1,"")
Copy that cell down to row 40 In cell B1 put the formula
=A1
In cell B2 put the formula
=B1 & A2
Copy that cell down to row 40.
The value you want is now in that column in row 40.
Not really the answer you want, but that is the fastest way to get things done excel wise without creating a custom formula that takes in a range and makes the calculation (which would be more fun to do).
@AlexanderMP's answer is correct, but you can also consider handling nulls with coalesce
:
declare @CodeNameString nvarchar(max)
set @CodeNameString = null
SELECT @CodeNameString = Coalesce(@CodeNameString + ', ', '') + cast(CodeName as varchar) from AccountCodes
select @CodeNameString
A little late to the party but in one line provided that you have glob2 and humanize installed. Note that in Python 3, the default iglob
has a recursive mode. How to modify the code for Python 3 is left as a trivial exercise for the reader.
>>> import os
>>> from humanize import naturalsize
>>> from glob2 import iglob
>>> naturalsize(sum(os.path.getsize(x) for x in iglob('/var/**'))))
'546.2 MB'
The below solution is the simplest one:
Console.WriteLine("[{0}]", string.Join(", ", array));
Output: [1, 2, 3, 4, 5]
Another short solution:
Array.ForEach(array, val => Console.Write("{0} ", val));
Output: 1 2 3 4 5
. Or if you need to add add ,
, use the below:
int i = 0;
Array.ForEach(array, val => Console.Write(i == array.Length -1) ? "{0}" : "{0}, ", val));
Output: 1, 2, 3, 4, 5
As Bakkal explained, for the keyboard shortcuts, in netbeans
you can go to tools->options->editor->code templates and add or edit your own shortcuts.
In Eclipse
it's on templates.
Do nothing to the browser. CORS is supported by default on all modern browsers (and since Firefox 3.5).
The server being accessed by JavaScript has to give the site hosting the HTML document in which the JS is running permission via CORS HTTP response headers.
security.fileuri.strict_origin_policy
is used to give JS in local HTML documents access to your entire hard disk. Don't set it to false
as it makes you vulnerable to attacks from downloaded HTML documents (including email attachments).
If you want all the fields in the form to inherit a certain class, you just define a parent class, that inherits from forms.ModelForm
, and then inherit from it
class BaseForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'someClass'
class WhateverForm(BaseForm):
class Meta:
model = SomeModel
This helped me to add the 'form-control'
class to all of the fields on all of the forms of my application automatically, without adding replication of code.
There is another option that does not introduce global gotchas when trying to initialize multiple variables to the same value. Whether or not it is preferable to the long way is a judgement call. It will likely be slower and may or may not be more readable. In your specific case, I think that the long way is probably more readable and maintainable as well as being faster.
The other way utilizes Destructuring assignment.
let [moveUp, moveDown,_x000D_
moveLeft, moveRight,_x000D_
mouseDown, touchDown] = Array(6).fill(false);_x000D_
_x000D_
console.log(JSON.stringify({_x000D_
moveUp, moveDown,_x000D_
moveLeft, moveRight,_x000D_
mouseDown, touchDown_x000D_
}, null, ' '));_x000D_
_x000D_
// NOTE: If you want to do this with objects, you would be safer doing this_x000D_
let [obj1, obj2, obj3] = Array(3).fill(null).map(() => ({}));_x000D_
console.log(JSON.stringify({_x000D_
obj1, obj2, obj3_x000D_
}, null, ' '));_x000D_
// So that each array element is a unique object_x000D_
_x000D_
// Or another cool trick would be to use an infinite generator_x000D_
let [a, b, c, d] = (function*() { while (true) yield {x: 0, y: 0} })();_x000D_
console.log(JSON.stringify({_x000D_
a, b, c, d_x000D_
}, null, ' '));_x000D_
_x000D_
// Or generic fixed generator function_x000D_
function* nTimes(n, f) {_x000D_
for(let i = 0; i < n; i++) {_x000D_
yield f();_x000D_
}_x000D_
}_x000D_
let [p1, p2, p3] = [...nTimes(3, () => ({ x: 0, y: 0 }))];_x000D_
console.log(JSON.stringify({_x000D_
p1, p2, p3_x000D_
}, null, ' '));
_x000D_
This allows you to initialize a set of var
, let
, or const
variables to the same value on a single line all with the same expected scope.
References:
MDN: Array Global Object
MDN: Array.fill
Edit:
Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs
See the working example: http://jsfiddle.net/U6aKT/
<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>
For integers:
public class Division {
public static void main(String[] args) {
System.out.println("Division: " + divide(100, 9));
}
public static int divide(int num, int divisor) {
int sign = 1;
if((num > 0 && divisor < 0) || (num < 0 && divisor > 0))
sign = -1;
return divide(Math.abs(num), Math.abs(divisor), Math.abs(divisor)) * sign;
}
public static int divide(int num, int divisor, int sum) {
if (sum > num) {
return 0;
}
return 1 + divide(num, divisor, sum + divisor);
}
}
You need to modify the method GetData()
and add your "experimental" code there, and return t1
.
ViewBag
is of type dynamic
but, is internally an System.Dynamic.ExpandoObject()
It is declared like this:
dynamic ViewBag = new System.Dynamic.ExpandoObject();
which is why you can do :
ViewBag.Foo = "Bar";
A Sample Expander Object Code:
public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
{
public Dictionary<string, object> objectDictionary;
public ExpanderObject()
{
objectDictionary = new Dictionary<string, object>();
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
object val;
if (objectDictionary.TryGetValue(binder.Name, out val))
{
result = val;
return true;
}
result = null;
return false;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
try
{
objectDictionary[binder.Name] = value;
return true;
}
catch (Exception ex)
{
return false;
}
}
}
In case of NULL
columns it is better to use IF
clause like this which combine the two functions of : CONCAT
and COALESCE
and uses special chars between the columns in result like space or '_'
SELECT FirstName , LastName ,
IF(FirstName IS NULL AND LastName IS NULL, NULL,' _ ',CONCAT(COALESCE(FirstName ,''), COALESCE(LastName ,'')))
AS Contact_Phone FROM TABLE1
You can also detect it like below
$.isIPhone = function(){
return ((navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1));
};
$.isIPad = function (){
return (navigator.platform.indexOf("iPad") != -1);
};
$.isAndroidMobile = function(){
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1 && ua.indexOf("mobile");
};
$.isAndroidTablet = function(){
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1 && !(ua.indexOf("mobile"));
};
500 Internal Server Error is shown if your php code has fatal errors but error displaying is switched off. You may try this to see the error itself instead of 500 error page:
In your php file:
ini_set('display_errors', 1);
In .htaccess file:
php_flag display_errors 1
Check the uploaded image size using Javascript
<script type="text/javascript">
function check(){
var imgpath=document.getElementById('imgfile');
if (!imgpath.value==""){
var img=imgpath.files[0].size;
var imgsize=img/1024;
alert(imgsize);
}
}
</script>
Html code
<form method="post" enctype="multipart/form-data" onsubmit="return check();">
<input type="file" name="imgfile" id="imgfile"><br><input type="submit">
</form>
With the help of dr answer, I wrote a workaround that makes the conversion to put in your .bashrc. It won't break anything if you don't have any timestamp or already correct timestamps.
dmesg_with_human_timestamps () {
$(type -P dmesg) "$@" | perl -w -e 'use strict;
my ($uptime) = do { local @ARGV="/proc/uptime";<>}; ($uptime) = ($uptime =~ /^(\d+)\./);
foreach my $line (<>) {
printf( ($line=~/^\[\s*(\d+)\.\d+\](.+)/) ? ( "[%s]%s\n", scalar localtime(time - $uptime + $1), $2 ) : $line )
}'
}
alias dmesg=dmesg_with_human_timestamps
Also, a good reading on the dmesg timestamp conversion logic & how to enable timestamps when there are none: https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk92677
I am answering bit late to this question, but someone, in future, might find this useful. The below approach, besides lots of other approaches, works best, and I personally think would better suit a web application.
@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
... other configurations
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
builder.serializationInclusion(Include.NON_EMPTY);
builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
}
}
FileInputStream fis = new FileInputStream(new File("C:/Test.xlsx"));
//create workbook instance
XSSFWorkbook wb = new XSSFWorkbook(fis);
//create a sheet object to retrieve the sheet
XSSFSheet sheet = wb.getSheetAt(0);
//to evaluate cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
for(Row row : sheet)
{
for(Cell cell : row)
{
switch(formulaEvaluator.evaluateInCell(cell).getCellTypeEnum())
{
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
default:
break;
}
}
System.out.println();
}
This code will work fine. Use getCellTypeEnum()
and to compare use just NUMERIC
or STRING
.
Just add these lines to your <script>
(somewhere after jQuery is loaded but before posting anything):
$.postJSON = function(url, data, func)
{
$.post(url, data, func, 'json');
}
Replace (some/all) $.getJSON
with $.postJSON
and enjoy!
You can use the same Javascript callback functions as with $.getJSON
.
No server-side change is needed. (Well, I always recommend using $_REQUEST
in PHP. http://php.net/manual/en/reserved.variables.request.php, Among $_REQUEST, $_GET and $_POST which one is the fastest?)
This is simpler than @lepe's solution.
in my case, i dont call at all "onCreate" (its a react native app and this can be fixes also by using the react-native StatusBar component) one can also use this:
override fun onStart() {
super.onStart()
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = Color.TRANSPARENT
}
To expand on the @PostConstruct
suggestion in other answers, this really is the best solution, in my opinion.
@PostConstruct
is in javax.*
)Requirement and test on Android Studio 3.5
Make sure your old project working properly with your existing android studio library.
Note: if adb run showing activity not found, edit your Run/Debug Configuration. Module should point to module application e.g. app.
Let say you have an exchange call like below:
String url = "/zzz/{accountNumber}";
Optional<AccountResponse> accResponse = Optional.ofNullable(accountNumber)
.map(account -> {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "bearer 121212");
HttpEntity<Object> entity = new HttpEntity<>(headers);
ResponseEntity<AccountResponse> response = template.exchange(
url,
GET,
entity,
AccountResponse.class,
accountNumber
);
return response.getBody();
});
To mock this in your test case you can use mocitko as below:
when(restTemplate.exchange(
ArgumentMatchers.anyString(),
ArgumentMatchers.any(HttpMethod.class),
ArgumentMatchers.any(),
ArgumentMatchers.<Class<AccountResponse>>any(),
ArgumentMatchers.<ParameterizedTypeReference<List<Object>>>any())
)
First of all, you tried to replace the entire 12.00 with '', which isn't going to give your desired results.
Second you are trying to do replace directly on a decimal. Replace must be performed on a string, so you have to CAST.
There are many ways to get your desired results, but this replace would have worked (assuming your column name is "height":
REPLACE(CAST(height as varchar(31)),'.00','')
EDIT:
This script works:
DECLARE @Height decimal(6,2);
SET @Height = 12.00;
SELECT @Height, REPLACE(CAST(@Height AS varchar(31)),'.00','');
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
You could write a jQuery function which allowed you to add hidden fields to a form:
// This must be applied to a form (or an object inside a form).
jQuery.fn.addHidden = function (name, value) {
return this.each(function () {
var input = $("<input>").attr("type", "hidden").attr("name", name).val(value);
$(this).append($(input));
});
};
And then add the hidden field before you submit:
var frm = $("#form").addHidden('SaveAndReturn', 'Save and Return')
.submit();
setTimeout
may help out here
$("#message_link").click(function(){
setTimeout(function() {
if (some_conditions...){
$("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\" /></div>");
}
}, 100);
});
That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.
This doesn't work and it shouldn't because it would be a giant security hole.
Have a look at the new File System API. It allows you to request access to a virtual, sandboxed filesystem governed by the browser. You will have to request your user to "upload" their file into the sandboxed filesystem once, but afterwards you can work with it very elegantly.
While this definitely is the future, it is still highly experimental and only works in Google Chrome as far as CanIUse knows.
this error messages means that CABundle is not given by (-CAfile ...) OR the CABundle file is not closed by a self-signed root certificate.
Don't worry. The connection to server will work even you get theis message from openssl s_client ... (assumed you dont take other mistake too)
This is because of using integer indices (ix
selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).
*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:
df.iloc[-3:]
see the docs.
As Wes points out, in this specific case you should just use tail!
You could try attaching handlers to various events of BitmapImage:
They might tell you a little about what's going on, as far as the image is concerned.
Create a new table called comments
They should have a column containing the id of the post they are assigned to.
Make a form which adds a new comment to that table.
An example (not tested so may contain lil' syntax errors): I call a page with comments a post
Post.php
<!-- Post content here -->
<!-- Then cmments below -->
<h1>Comments</h1>
<?php
$result = mysql_query("SELECT * FROM comments WHERE postid=0");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <?php echo $row->author; //Or similar in your table ?>
<p>
<?php echo;$row->body; ?>
</p>
</div>
<?php
}
?>
<h1>Leave a comment:</h1>
<form action="insertcomment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="hidden" name="postid" value="<?php //your posts id ?>" />
<input type="submit" />
</form>
insertcomment.php
<?php
//First check if everything is filled in
if(/*some statements*/)
{
//Do a mysql_real_escape_string() to all fields
//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>
You must change the code a bit to make it work. I'n not doing your homework. Only a part of it ;)
Go to Project | Properties and then Assembly Information and then Assembly Version and put an * in the last or the second-to-last box (you can't auto-increment the Major or Minor components).
This is tested in android 7.0 up to android 10.0 and it works
Use these codes to check if string contains space/spaces may it be in the first position, middle or last:
name = firstname.getText().toString(); //name is the variable that holds the string value
Pattern space = Pattern.compile("\\s+");
Matcher matcherSpace = space.matcher(name);
boolean containsSpace = matcherSpace.find();
if(constainsSpace == true){
//string contains space
}
else{
//string does not contain any space
}
No, you can't. The compiler doesn't know what the pointer is pointing to. There are tricks, like ending the array with a known out-of-band value and then counting the size up until that value, but that's not using sizeof()
.
Another trick is the one mentioned by Zan, which is to stash the size somewhere. For example, if you're dynamically allocating the array, allocate a block one int bigger than the one you need, stash the size in the first int, and return ptr+1
as the pointer to the array. When you need the size, decrement the pointer and peek at the stashed value. Just remember to free the whole block starting from the beginning, and not just the array.
I am assuming you are using Eclipse as your developing environment.
Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.
Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.
The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error
This is another way:
{{some_str | limitTo:1 | uppercase}}{{some_str.substr(1) | lowercase }}
Cinn's answer is great, but there's one thing wrong with it.
The PreferredSize
widget will start immediately at the top of the screen, without accounting for the status bar, so some of its height will be shadowed by the status bar's height. This also accounts for the side notches.
The solution: Wrap the preferredSize
's child with a SafeArea
appBar: PreferredSize(
//Here is the preferred height.
preferredSize: Size.fromHeight(50.0),
child: SafeArea(
child: AppBar(
flexibleSpace: ...
),
),
),
If you don't wanna use the flexibleSpace property, then there's no need for all that, because the other properties of the AppBar
will account for the status bar automatically.
You can try this new library. JellyGif respects Gif frame duration while being highly CPU & Memory performant. It works great with UITableViewCell & UICollectionViewCell too. To get started you just need to
import JellyGif
let imageView = JellyGifImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
//Animates Gif from the main bundle
imageView.startGif(with: .name("Gif name"))
//Animates Gif with a local path
let url = URL(string: "Gif path")!
imageView.startGif(with: .localPath(url))
//Animates Gif with data
imageView.startGif(with: .data(Data))
For more information you can look at its README
I had this problem with Firefox and my server. I contacted GoDaddy customer support, and they had me install the intermediate server certificate:
http://support.godaddy.com/help/article/868/what-is-an-intermediate-certificate
After a re-start of the World Wide Web Publishing Service, everything worked perfectly.
If you do not have full access to your server, your ISP will have to do this for you.
You want this
document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID">...</div>' );
While a comprehensive answer to this question takes up hundreds of pages of my book, here's a quick comparison chart that I'm still working on:
Maybe this will satisfy you -
something.xml
<CheckBox
android:text="Custom CheckBox"
android:button="@drawable/checkbox_selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/star_down" />
<item android:state_checked="false" android:drawable="@drawable/star" />
</selector>
For, the reference just refer here
You were looking for help on installations with pip. You can find it with the following command:
pip install --help
Running pip install -e /path/to/package
installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.
This statement will definitely help you:
env = env.OrderByDescending(c => c.ReportDate).ToList();
The best operator for strict checking is
if($foo === true){}
That way, you're really checking if its true, and not 1 or simply just set.
Recent update from Developer.Android.com
Don't work with MAC addresses MAC addresses are globally unique, not user-resettable, and survive factory resets. For these reasons, it's generally not recommended to use MAC address for any form of user identification. Devices running Android 10 (API level 29) and higher report randomized MAC addresses to all apps that aren't device owner apps.
Between Android 6.0 (API level 23) and Android 9 (API level 28), local device MAC addresses, such as Wi-Fi and Bluetooth, aren't available via third-party APIs. The WifiInfo.getMacAddress() method and the BluetoothAdapter.getDefaultAdapter().getAddress() method both return 02:00:00:00:00:00.
Additionally, between Android 6.0 and Android 9, you must hold the following permissions to access MAC addresses of nearby external devices available via Bluetooth and Wi-Fi scans:
Method/Property Permissions Required
ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
According to pip documentation example 3:
pip install --upgrade django
But based on my experience, using this method will also upgrade any package related to it. Example:
Assume you want to upgrade somepackage
that require Django >= 1.2.4
using this kind of method it will also upgrade somepackage
and django
to the newest update. Just to be safe, do:
# Assume you want to keep Django 1.2.4
pip install --upgrade somepackage django==1.2.4
Doing this will upgrade somepackage
and keeping Django to the 1.2.4 version.
You might want to have a look at Process Lasso.
For macOS catalina try this : open Xcode. if not existing. download from App store (about 11GB) then open Xcode>open developer tool>more developer tool and used my apple id to download a compatible command line tool. Then, after downloading, I opened Xcode>Preferences>Locations>Command Line Tool and selected the newly downloaded command line tool from downloads.
You are getting an HTTP 400
(Bad Request) error because there is a space
in your URL. If you fix it (before the zoom
parameter), you will get an HTTP 400
error (Unauthorized).
Maybe you need some HTTP header to identify your download as a recognised browser (use the "User-Agent" header) or additional authentication parameter.
For the User-Agent example, then use the ImageIO.read(InputStream) using the connection inputstream:
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "xxxxxx");
Use whatever needed for xxxxxx
For sure: qsort()
is an implementation of a sort (not necessarily quicksort as its name might suggest).
Try man 3 qsort or have a read at http://linux.die.net/man/3/qsort
For v4.0.7 You can increase the height by overriding CSS classes like this example:
.select2-container .select2-selection--single {
height: 36px;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
line-height: 36px;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
height: 36px;
}
Use -exec
:
"your-script-name": "nodemon [options] --exec 'npm start -s'"
You don't free anything at all. Since you never acquired any resources dynamically, there is nothing you have to, or even are allowed to, free.
(It's the same as when you say int n = 10;
: There are no dynamic resources involved that you have to manage manually.)
You need to run the .datepicker();
again after you've dynamically created the other textbox elements.
I would recommend doing so in the callback method of the call that is adding the elements to the DOM.
So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:
$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
$(".datepicker_recurring_start" ).datepicker();
});
Beyond definitions, which are sometimes understandable only if you already understand, an example helped me.
I think I got a glimmer of understanding when loooking at sorting a list in .Net; an example of a framework providing a functionality that's tailored by user code providing specific functionality. Take List.Sort(IComparer). The sort algorithm, which resides in the .Net framework in the Sort method, needs to do a series of compares; does object A come before or after object B? But Sort itself has no clue how to do the compare; only the type being sorted knows that. You couldn't write a comparison sort algorithm that can be reused by many users and anticipate all the various types you'd be called upon to sort. You've got to leave that bit of work up to the user itself. So here, sort, aka the framework, calls back to a method in the user code, the type being sorted so it can do the compare. (Or a delegate can be used; same point.)
Did I get this right?
Honestly?
"What is .NET?"
If they can give you a clear answer as to what .NET is and what it isn't, how it's used, what elements it's composed of, etc... If they can convince you they know what it is, then chances are they know it pretty well.
The fact of the matter is, many people don't really know what .NET is. Even those who write programs for it.
Use fcron (http://fcron.free.fr/) - gives you granularity in seconds and way better and more feature rich than cron (vixie-cron) and stable too. I used to make stupid things like having about 60 php scripts running on one machine in very stupid settings and it still did its job!
NOTE: history.pushState()
is now supported - see other answers.
You cannot change the whole url without redirecting, what you can do instead is change the hash.
The hash is the part of the url that goes after the # symbol. That was initially intended to direct you (locally) to sections of your HTML document, but you can read and modify it through javascript to use it somewhat like a global variable.
If applied well, this technique is useful in two ways:
To change the hash you can do:
document.location.hash = "show_picture";
To watch for hash changes you have to do something like:
window.onhashchange = function(){
var what_to_do = document.location.hash;
if (what_to_do=="#show_picture")
show_picture();
}
Of course the hash is just a string, so you can do pretty much what you like with it. For example you can put a whole object there if you use JSON to stringify it.
There are very good JQuery libraries to do advanced things with that.
if (strpos($string, $word) === FALSE) {
... not found ...
}
Note that strpos()
is case sensitive, if you want a case-insensitive search, use stripos()
instead.
Also note the ===
, forcing a strict equality test. strpos CAN return a valid 0
if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.
I was facing issue. The tools
folder was also missing from the Android SDK
folder. I believe tools
folder appears only after installing Android SDL tools(obsolete
). This option was not available for me.
Solution:
I upgraded the Java
from version 8 to version 12 and I was able to install the tools. You may still get the error Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses
while giving the command flutter doctor -v
. Run the command flutter doctor --android-licenses
, the licences will be reviewed when you click yes
every time this question appears Accept? (y/N):
Hopefully it will help someone.
2017 update: Object.values, lodash values and toArray do it. And to preserve keys map and spread operator play nice:
// import { toArray, map } from 'lodash'_x000D_
const map = _.map_x000D_
_x000D_
const input = {_x000D_
key: {_x000D_
value: 'value'_x000D_
}_x000D_
}_x000D_
_x000D_
const output = map(input, (value, key) => ({_x000D_
key,_x000D_
...value_x000D_
}))_x000D_
_x000D_
console.log(output)_x000D_
// >> [{key: 'key', value: 'value'}])
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
This will add all unknown (except ignored) files under the specified directory tree:
svn add --force path/to/dir
This will add all unknown (except ignored) files in the current directory and below:
svn add --force .
You can use:
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
Use this command
git checkout -b old-state 0d1d7fc32
I'm not sure about best practice, but here is how I do it:
/*
* Object Constructor
*/
var foo = function(x) {
this.x = x;
};
/*
* Object Protoype
*/
foo.prototype = {
/*
* f is the name that is going to be used to call the various overloaded versions
*/
f: function() {
/*
* Save 'this' in order to use it inside the overloaded functions
* because there 'this' has a different meaning.
*/
var that = this;
/*
* Define three overloaded functions
*/
var f1 = function(arg1) {
console.log("f1 called with " + arg1);
return arg1 + that.x;
}
var f2 = function(arg1, arg2) {
console.log("f2 called with " + arg1 + " and " + arg2);
return arg1 + arg2 + that.x;
}
var f3 = function(arg1) {
console.log("f3 called with [" + arg1[0] + ", " + arg1[1] + "]");
return arg1[0] + arg1[1];
}
/*
* Use the arguments array-like object to decide which function to execute when calling f(...)
*/
if (arguments.length === 1 && !Array.isArray(arguments[0])) {
return f1(arguments[0]);
} else if (arguments.length === 2) {
return f2(arguments[0], arguments[1]);
} else if (arguments.length === 1 && Array.isArray(arguments[0])) {
return f3(arguments[0]);
}
}
}
/*
* Instantiate an object
*/
var obj = new foo("z");
/*
* Call the overloaded functions using f(...)
*/
console.log(obj.f("x")); // executes f1, returns "xz"
console.log(obj.f("x", "y")); // executes f2, returns "xyz"
console.log(obj.f(["x", "y"])); // executes f3, returns "xy"
If you are loading images, you are likely going to be working with one or both of matplotlib
and opencv
to manipulate and view the images.
For this reason, I tend to use their image readers and append those to lists, from which I make a NumPy array.
import os
import matplotlib.pyplot as plt
import cv2
import numpy as np
# Get the file paths
im_files = os.listdir('path/to/files/')
# imagine we only want to load PNG files (or JPEG or whatever...)
EXTENSION = '.png'
# Load using matplotlib
images_plt = [plt.imread(f) for f in im_files if f.endswith(EXTENSION)]
# convert your lists into a numpy array of size (N, H, W, C)
images = np.array(images_plt)
# Load using opencv
images_cv = [cv2.imread(f) for f in im_files if f.endswith(EXTENSION)]
# convert your lists into a numpy array of size (N, C, H, W)
images = np.array(images_cv)
The only difference to be aware of is the following:
So a single image that is 256*256 in size would produce matrices of size (3, 256, 256) with opencv and (256, 256, 3) using matplotlib.
Here is some food for thought.
If you had been using all .htm files on your website and now, for example, you have changed the editor that you are using, and your new editor is outputting all your files with the .html extension. When you re-publish your site to the server, it would seem to me that you could really hurt your SEO position/ranking as many of the links out there in the web, including Google, that were looking for the .htm and not the new .html for that same page. This assumes that you are still using the same page names from your old editor which would make sense.
Anyway... My point is, be careful not to loose that link juice you have build up. So I guess in this example, there is a reason to stick with .htm... But other then that as mentioned by everyone else they seem to be the same.
Please correct if I'm wrong.
The reason I mention all this is because this is what I was in the process of doing when it occurred to me I may be damaging the site SEO with the new editor.
The original editor was MS Front Page, which always outputted .htm, dead now, and the new editor "90 Second Web Builder 9" which outputs all .html files... Luckily, they must have thought about this and they included a way to change the output extension back to .htm
Anyway, that's my 2 cents... hope it helps someone..
Response.Write('... javascript that opens a window...')
Place the ico address in the head
with a link
-tag:
<link rel="shortcut icon" href="http://sstatic.net/stackoverflow/img/favicon.ico">
Bootstrap 4+ has made changes to the utility classes for this. From the documentation:
Added
.float-{sm,md,lg,xl}-{left,right,none}
classes for responsive floats and removed.pull-left
and.pull-right
since they’re redundant to.float-left
and.float-right
.
So use the .float-right
(or a size equivalent such as .float-lg-right
) instead of .pull-right
for your right alignment if you're using a newer Bootstrap version.
Comma-separated items enclosed by (
and )
are tuple
s, those enclosed by [
and ]
are list
s.
This usually occurs when you uninstalling the App you are developing. Check whether you have activated the guest account, if so switch the account and uninstall the app, switch back to Admin user (You). and carry on!
My favoured technique:
signal clk : std_logic := '0'; -- make sure you initialise!
...
clk <= not clk after half_period;
I usually extend this with a finished
signal to allow me to stop the clock:
clk <= not clk after half_period when finished /= '1' else '0';
Gotcha alert:
Care needs to be taken if you calculate half_period
from another constant by dividing by 2. The simulator has a "time resolution" setting, which often defaults to nanoseconds... In which case, 5 ns / 2
comes out to be 2 ns
so you end up with a period of 4ns! Set the simulator to picoseconds and all will be well (until you need fractions of a picosecond to represent your clock time anyway!)
Answer: document.activeElement
To do what you want, use document.activeElement.blur()
If you need to support Firefox 2, you can also use this:
function onElementFocused(e)
{
if (e && e.target)
document.activeElement = e.target == document ? null : e.target;
}
if (document.addEventListener)
document.addEventListener("focus", onElementFocused, true);
The count
method of NSArray
returns an NSUInteger
, and on the 64-bit OS X platform
NSUInteger
is defined as unsigned long
, andunsigned long
is a 64-bit unsigned integer.int
is a 32-bit integer.So int
is a "smaller" datatype than NSUInteger
, therefore the compiler warning.
See also NSUInteger in the "Foundation Data Types Reference":
When building 32-bit applications, NSUInteger is a 32-bit unsigned integer. A 64-bit application treats NSUInteger as a 64-bit unsigned integer.
To fix that compiler warning, you can either declare the local count
variable as
NSUInteger count;
or (if you are sure that your array will never contain more than 2^31-1
elements!),
add an explicit cast:
int count = (int)[myColors count];
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
I encountered the same problem, and finally found a way:
Ecplise Version: Mars.2 Release (4.5.2)
For Me I just wanted to see the error in my VBA application so in the function I created the below code..
Function Database_FileRpt
'-------------------------
On Error GoTo CleanFail
'-------------------------
'
' Create_DailyReport_Action and code
CleanFail:
'*************************************
MsgBox "********************" _
& vbCrLf & "Err.Number: " & Err.Number _
& vbCrLf & "Err.Description: " & Err.Description _
& vbCrLf & "Err.Source: " & Err.Source _
& vbCrLf & "********************" _
& vbCrLf & "...Exiting VBA Function: Database_FileRpt" _
& vbCrLf & "...Excel VBA Program Reset." _
, , "VBA Error Exception Raised!"
*************************************
' Note that the next line will reset the error object to 0, the variables
above are used to remember the values
' so that the same error can be re-raised
Err.Clear
' *************************************
Resume CleanExit
CleanExit:
'cleanup code , if any, goes here. runs regardless of error state.
Exit Function ' SUB or Function
End Function ' end of Database_FileRpt
' ------------------
The quick and dirty way I use to export mysql output to a file is
$ mysql <database_name> --tee=<file_path>
and then use the exported output (which you can find in <file_path>
) wherever I want.
Note that this is the only way you have in order to avoid databases running using the secure-file-priv
option, which prevents the usage of INTO OUTFILE
suggested in the previous answers:
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
yield
?The yield
keyword returns data from a generator function:
The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.
A generator function is effectively a more compact and efficient way to write an Iterator. It allows you to define a function (your xrange
) that will calculate and return values while you are looping over it:
function xrange($min, $max) {
for ($i = $min; $i <= $max; $i++) {
yield $i;
}
}
[…]
foreach (xrange(1, 10) as $key => $value) {
echo "$key => $value", PHP_EOL;
}
This would create the following output:
0 => 1
1 => 2
…
9 => 10
You can also control the $key
in the foreach
by using
yield $someKey => $someValue;
In the generator function, $someKey
is whatever you want appear for $key
and $someValue
being the value in $val
. In the question's example that's $i
.
Now you might wonder why we are not simply using PHP's native range
function to achieve that output. And right you are. The output would be the same. The difference is how we got there.
When we use range
PHP, will execute it, create the entire array of numbers in memory and return
that entire array to the foreach
loop which will then go over it and output the values. In other words, the foreach
will operate on the array itself. The range
function and the foreach
only "talk" once. Think of it like getting a package in the mail. The delivery guy will hand you the package and leave. And then you unwrap the entire package, taking out whatever is in there.
When we use the generator function, PHP will step into the function and execute it until it either meets the end or a yield
keyword. When it meets a yield
, it will then return whatever is the value at that time to the outer loop. Then it goes back into the generator function and continues from where it yielded. Since your xrange
holds a for
loop, it will execute and yield until $max
was reached. Think of it like the foreach
and the generator playing ping pong.
Obviously, generators can be used to work around memory limits. Depending on your environment, doing a range(1, 1000000)
will fatal your script whereas the same with a generator will just work fine. Or as Wikipedia puts it:
Because generators compute their yielded values only on demand, they are useful for representing sequences that would be expensive or impossible to compute at once. These include e.g. infinite sequences and live data streams.
Generators are also supposed to be pretty fast. But keep in mind that when we are talking about fast, we are usually talking in very small numbers. So before you now run off and change all your code to use generators, do a benchmark to see where it makes sense.
Another Use Case for Generators is asynchronous coroutines. The yield
keyword does not only return values but it also accepts them. For details on this, see the two excellent blog posts linked below.
yield
?Generators have been introduced in PHP 5.5. Trying to use yield
before that version will result in various parse errors, depending on the code that follows the keyword. So if you get a parse error from that code, update your PHP.
I believe this is what you're looking for:
Convert Decimal Numbers to Text showing only the non-zero decimals
Especially this line might be helpful:
StringVar text := Totext ( {Your.NumberField} , 6 , "" ) ;
The first parameter is the decimal to be converted, the second parameter is the number of decimal places and the third parameter is the separator for thousands/millions etc.
DO NOT USE MYSQL ANY MORE. If you must use mysqli but PDO is best:
$pdo = new PDO($dsn, $username, $pdo); // proper PDO init string here
if ($pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name'")->fetch()) // table exists.
You should be able to do the following:
MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
if (test != null && test.isVisible()) {
//DO STUFF
}
else {
//Whatever
}
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
If you write a function then once you leave it all names inside disappear.
The concept is called namespace and it's so good, it made it into the Zen of Python:
Namespaces are one honking great idea -- let's do more of those!
The namespace of IPython can likewise be reset with the magic command %reset -f
. (The -f
means "force"; in other words, "don't ask me if I really want to delete all the variables, just do it.")
Yes it is valid according to xhtml1-strict.dtd
. The following XHTML passes the validation:
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<ul>
<li><div>test</div></li>
</ul>
</body>
</html>
"instance to an application" means nothing.
"object" and "instance" are the same thing. There is a "class" that defines structure, and instances of that class (obtained with new ClassName()
). For example there is the class Car
, and there are instance with different properties like mileage, max speed, horse-power, brand, etc.
Reference is, in the Java context, a variable* - it is something pointing to an object/instance. For example, String s = null;
- s
is a reference, that currently references no instance, but can reference an instance of the String
class.
*Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method - pass-by-value.
The value of s is a reference. It's very important to distinguish between variables and values, and objects and references.
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.
Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.
It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."
Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.
There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.
In a recent project, I had to update the Kendo UI Grid based on some calls, that were happening on some dropdown selects. Here is what I ended up using:
$.ajax({
url: '/api/....',
data: { myIDSArray: javascriptArrayOfIDs },
traditional: true,
success: function(result) {
searchResults = result;
}
}).done(function() {
var dataSource = new kendo.data.DataSource({ data: searchResults });
var grid = $('#myKendoGrid').data("kendoGrid");
dataSource.read();
grid.setDataSource(dataSource);
});
Hopefully this will save you some time.
Use SVD or QR-decomposition to calculate exact solution in real or complex number fields:
numpy.linalg.svd numpy.linalg.qr
char* str = "HELLO";
char c = str[1];
Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0]
, "E" is str[1]
, the first "L" is str[2]
and so on.
__FUNCTION__
is non standard, __func__
exists in C99 / C++11. The others (__LINE__
and __FILE__
) are just fine.
It will always report the right file and line (and function if you choose to use __FUNCTION__
/__func__
). Optimization is a non-factor since it is a compile time macro expansion; it will never affect performance in any way.
You can do it by listening to phone call events . You do it by having a BroadcastReceiver to PHONE_STATE and to NEW_OUTGOING_CALL. You find there what is the phone number.
Then when you decide to end the call, this is a bit tricky, because only from Android P it's guaranteed to work. Check here.
It's possible that you have mixed tabs and spaces in your file. You can have python help check for such errors with
python -m tabnanny <name of python file>