let text:String = "Hello Friend"
let searchRange:NSRange = NSRange(location:0,length: text.characters.count)
let range:Range`<Int`> = Range`<Int`>.init(start: searchRange.location, end: searchRange.length)
// Search string exist in employee name finding.
var empName:NSString! = employeeDetails[filterKeyString] as NSString
Case sensitve search.
let rangeOfSearchString:NSRange! = empName.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch)
// Not found.
if rangeOfSearchString.location != Foundation.NSNotFound
{
// search string not found in employee name.
}
// Found
else
{
// search string found in employee name.
}
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
This worked for me on Safari 5 on Mac OSX, jQuery 1.4:
$("Selector")[elementIx].selectionStart = desiredStartPos;
$("Selector")[elementIx].selectionEnd = desiredEndPos;
I had the same problem try this:
python manage.py sqlsequencereset table_name
Eg:
python manage.py sqlsequencereset auth
you need to run this in production settings(if you have) and you need Postgres installed to run this on the server
The auto keyword gets the type from the expression on the right of =. Therefore it will work with any type, the only requirement is to initialize the auto variable when declaring it so that the compiler can deduce the type.
Examples:
auto a = 0.0f; // a is float
auto b = std::vector<int>(); // b is std::vector<int>()
MyType foo() { return MyType(); }
auto c = foo(); // c is MyType
You need a dependency property for this:
public BindingList<User> Users
{
get { return (BindingList<User>)GetValue(UsersProperty); }
set { SetValue(UsersProperty, value); }
}
public static readonly DependencyProperty UsersProperty =
DependencyProperty.Register("Users", typeof(BindingList<User>),
typeof(OptionsDialog));
Once that is done, you bind the checkbox to the dependency property:
<CheckBox x:Name="myCheckBox"
IsChecked="{Binding ElementName=window1, Path=CheckBoxIsChecked}" />
For that to work you have to name your Window or UserControl in its openning tag, and use that name in the ElementName parameter.
With this code, whenever you change the property on the code side, you will change the textbox. Also, whenever you check/uncheck the textbox, the Dependency Property will change too.
EDIT:
An easy way to create a dependency property is typing the snippet propdp, which will give you the general code for Dependency Properties.
All the code:
XAML:
<Window x:Class="StackOverflowTests.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" x:Name="window1" Height="300" Width="300">
<Grid>
<StackPanel Orientation="Vertical">
<CheckBox Margin="10"
x:Name="myCheckBox"
IsChecked="{Binding ElementName=window1, Path=IsCheckBoxChecked}">
Bound CheckBox
</CheckBox>
<Label Content="{Binding ElementName=window1, Path=IsCheckBoxChecked}"
ContentStringFormat="Is checkbox checked? {0}" />
</StackPanel>
</Grid>
</Window>
C#:
using System.Windows;
namespace StackOverflowTests
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public bool IsCheckBoxChecked
{
get { return (bool)GetValue(IsCheckBoxCheckedProperty); }
set { SetValue(IsCheckBoxCheckedProperty, value); }
}
// Using a DependencyProperty as the backing store for
//IsCheckBoxChecked. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsCheckBoxCheckedProperty =
DependencyProperty.Register("IsCheckBoxChecked", typeof(bool),
typeof(Window1), new UIPropertyMetadata(false));
public Window1()
{
InitializeComponent();
}
}
}
Notice how the only code behind is the Dependency Property. Both the label and the checkbox are bound to it. If the checkbox changes, the label changes too.
In short, it happens when the application which writes to the sqlite database does not have write permission.
This can be solved in three ways:
db.sqlite3
file and its parent directory (thereby write access also) to the user using chown (Eg: chown username db.sqlite3
)sudo -i
before you run gunicorn
or django runserver
)chmod 777 db.sqlite3
(Dangerous option)Never go for the third option unless you are running the webserver in a local machine or the data in the database is not at all important for you.
Second option is also not recommended. But you can go for it, if you are sure that your application is not vulnerable for code injection attack.
An additional consideraion that I have not seen in the answers already given, is that included columns can be of data types that are not allowed as index key columns, such as varchar(max).
This allows you to include such columns in a covering index. I recently had to do this to provide a nHibernate generated query, which had a lot of columns in the SELECT, with a useful index.
I have seen most of the articles that don't work properly that's why new developers and professional developers get confused about it.
I am explaining to you in a very simple way. In this code, I am generating a google Recaptcha token at the client side at every 3 seconds of time interval because the token is valid for only a few minutes that's why if any user takes time to fill the form then it may be expired.
First I have an index.php file where I am going to write HTML and JavaScript code.
<!DOCTYPE html>
<html>
<head>
<title>Google Recaptcha V3</title>
</head>
<body>
<h1>Google Recaptcha V3</h1>
<form action="recaptcha.php" method="post">
<label>Name</label>
<input type="text" name="name" id="name">
<input type="hidden" name="token" id="token" />
<input type="hidden" name="action" id="action" />
<input type="submit" name="submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
grecaptcha.ready(function() {
grecaptcha.execute('put your site key here', {action: 'application_form'}).then(function(token) {
$('#token').val(token);
$('#action').val('application_form');
});
});
}, 3000);
});
</script>
</body>
</html>
Next, I have created recaptcha.php file to execute it at the server side
<?php
if ($_POST['submit']) {
$name = $_POST['name'];
$token = $_POST['token'];
$action = $_POST['action'];
$curlData = array(
'secret' => 'put your secret key here',
'response' => $token
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($curlData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($ch);
$captchaResponse = json_decode($curlResponse, true);
if ($captchaResponse['success'] == '1' && $captchaResponse['action'] == $action && $captchaResponse['score'] >= 0.5 && $captchaResponse['hostname'] == $_SERVER['SERVER_NAME']) {
echo 'Form Submitted Successfully';
} else {
echo 'You are not a human';
}
}
Source of this code. If you would like to know the explanation of this code please visit. Google reCAPTCHA V3 integration in PHP
if anyone is interested to see the super simple solution written in Kotlin, check the blogpost I just created. The example in the blogpost is based on creating Sectioned RecyclerView:
https://brona.blog/2020/06/sectioned-recyclerview-in-three-steps/
I agree with Honest Abe that the match(...)
in the given examples are different. They are not a one-to-one comparisons and thus, outcomes are vary. To simplify my reply, I use A, B, C, D for those functions in question. Oh yes, we are dealing with 4 functions in re.py
instead of 3.
Running this piece of code:
h = re.compile('hello') # (A)
h.match('hello world') # (B)
is same as running this code:
re.match('hello', 'hello world') # (C)
Because, when looked into the source re.py
, (A + B) means:
h = re._compile('hello') # (D)
h.match('hello world')
and (C) is actually:
re._compile('hello').match('hello world')
So, (C) is not the same as (B). In fact, (C) calls (B) after calling (D) which is also called by (A). In other words, (C) = (A) + (B)
. Therefore, comparing (A + B) inside a loop has same result as (C) inside a loop.
George's regexTest.py
proved this for us.
noncompiled took 4.555 seconds. # (C) in a loop
compiledInLoop took 4.620 seconds. # (A + B) in a loop
compiled took 2.323 seconds. # (A) once + (B) in a loop
Everyone's interest is, how to get the result of 2.323 seconds. In order to make sure compile(...)
only get called once, we need to store the compiled regex object in memory. If we are using a class, we could store the object and reuse when every time our function get called.
class Foo:
regex = re.compile('hello')
def my_function(text)
return regex.match(text)
If we are not using class (which is my request today), then I have no comment. I'm still learning to use global variable in Python, and I know global variable is a bad thing.
One more point, I believe that using (A) + (B)
approach has an upper hand. Here are some facts as I observed (please correct me if I'm wrong):
Calls A once, it will do one search in the _cache
followed by one sre_compile.compile()
to create a regex object. Calls A twice, it will do two searches and one compile (because the regex object is cached).
If the _cache
get flushed in between, then the regex object is released from memory and Python need to compile again. (someone suggest that Python won't recompile.)
If we keep the regex object by using (A), the regex object will still get into _cache and get flushed somehow. But our code keep a reference on it and the regex object will not be released from memory. Those, Python need not to compile again.
The 2 seconds differences in George's test compiledInLoop vs compiled is mainly the time required to build the key and search the _cache. It doesn't mean the compile time of regex.
George's reallycompile test show what happen if it really re-do the compile every time: it will be 100x slower (he reduced the loop from 1,000,000 to 10,000).
Here are the only cases that (A + B) is better than (C):
Case that (C) is good enough:
Just a recap, here are the A B C:
h = re.compile('hello') # (A)
h.match('hello world') # (B)
re.match('hello', 'hello world') # (C)
Thanks for reading.
All of these schemes, except AES and Blowfish, have known vulnerabilities and should not be used.
However, Blowfish has been replaced by Twofish.
It depends on the jQuery selector that you use. Since id
should be unique within the DOM, the first one would be simple:
$('#Comanda').hide();
The second one might require something more, depending on the other elements and how to uniquely identify it. If the name
of that particular input
is unique, then this would work:
$('input[name="Vizualizeaza"]').hide();
Callable is a type or class of "Build-in function or Method" with a method call
>>> type(callable)
<class 'builtin_function_or_method'>
>>>
Example: print is a callable object. With a build-in function __call__ When you invoke the print function, Python creates an object of type print and invokes its method __call__ passing the parameters if any.
>>> type(print)
<class 'builtin_function_or_method'>
>>> print.__call__(10)
10
>>> print(10)
10
>>>
Thank you. Regards, Maris
Checkout the .SaveAs()
method in Excel object.
wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
Or following:
public static void SaveAs()
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];
Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];
thisCell.Value2 = "This is a test.";
wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.Close(false, "", true);
}
getline
, as it name states, read a whole line, or at least till a delimiter that can be specified.
So the answer is "no", getline
does not match your need.
But you can do something like:
inFile >> first_name >> last_name >> age;
name = first_name + " " + last_name;
try this... obviously you need to set each div to 25%. You then will need to add your content as needed :) Hope that helps.
<html>
<head>
<title>CSS devide window by 25% horizontally</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<style type="text/css" media="screen">
body {
margin:0;
padding:0;
height:100%;
}
#top_div
{
height:25%;
width:100%;
background-color:#009900;
margin:auto;
text-align:center;
}
#mid1_div
{
height:25%;
width:100%;
background-color:#990000;
margin:auto;
text-align:center;
color:#FFFFFF;
}
#mid2_div
{
height:25%;
width:100%;
background-color:#000000;
margin:auto;
text-align:center;
color:#FFFFFF;
}
#bottom_div
{
height:25%;
width:100%;
background-color:#990000;
margin:auto;
text-align:center;
color:#FFFFFF;
}
</style>
</head>
<body>
<div id="top_div">Top- height is 25% of window height</div>
<div id="mid1_div">Middle 1 - height is 25% of window height</div>
<div id="mid2_div">Middle 2 - height is 25% of window height</div>
<div id="bottom_div">Bottom - height is 25% of window height</div>
</body>
</html>
Tested and works fine, copy the code above into a HTML file, and open with your browser.
As of Java 8, you can use a lambda to capture parameters that are effectively final. For example:
final String param1 = "First param";
final int param2 = 2;
new Thread(() -> {
// Do whatever you want here: param1 and param2 are in-scope!
System.out.println(param1);
System.out.println(param2);
}).start();
To print stacktrace of Error
in console in more readable way:
console.log(ex, ex.stack.split("\n"));
Example result:
[Error] [ 'Error',
' at repl:1:7',
' at REPLServer.self.eval (repl.js:110:21)',
' at Interface.<anonymous> (repl.js:239:12)',
' at Interface.EventEmitter.emit (events.js:95:17)',
' at Interface._onLine (readline.js:202:10)',
' at Interface._line (readline.js:531:8)',
' at Interface._ttyWrite (readline.js:760:14)',
' at ReadStream.onkeypress (readline.js:99:10)',
' at ReadStream.EventEmitter.emit (events.js:98:17)',
' at emitKey (readline.js:1095:12)' ]
The warning:
deprecated conversion from string constant to 'char*'
is given because you are doing somewhere (not in the code you posted) something like:
void foo(char* str);
foo("hello");
The problem is that you are trying to convert a string literal (with type const char[]
) to char*
.
You can convert a const char[]
to const char*
because the array decays to the pointer, but what you are doing is making a mutable a constant.
This conversion is probably allowed for C compatibility and just gives you the warning mentioned.
Whoever wants UML deserves Rational Rose :)
JSONP does not work with basic authentication so the jQuery beforeSend callback won't work with JSONP/Script.
I managed to work around this limitation by adding the user and password to the request (e.g. user:[email protected]). This works with pretty much any browser except Internet Explorer where authentication through URLs is not supported (the call will simply not be executed).
Sadly, Java does not have multi-line string literals. You either have to concatenate string literals (using + or StringBuilder being the two most common approaches to this) or read the string in from a separate file.
For large multi-line string literals I'd be inclined to use a separate file and read it in using getResourceAsStream()
(a method of the Class
class). This makes it easy to find the file as you don't have to worry about the current directory versus where your code was installed. It also makes packaging easier, because you can actually store the file in your jar file.
Suppose you're in a class called Foo. Just do something like this:
Reader r = new InputStreamReader(Foo.class.getResourceAsStream("filename"), "UTF-8");
String s = Utils.readAll(r);
The one other annoyance is that Java doesn't have a standard "read all of the text from this Reader into a String" method. It's pretty easy to write though:
public static String readAll(Reader input) {
StringBuilder sb = new StringBuilder();
char[] buffer = new char[4096];
int charsRead;
while ((charsRead = input.read(buffer)) >= 0) {
sb.append(buffer, 0, charsRead);
}
input.close();
return sb.toString();
}
Another option is to use the JMSSerializerBundle. In your controller you then do
$serializer = $this->container->get('serializer');
$reports = $serializer->serialize($doctrineobject, 'json');
return new Response($reports); // should be $reports as $doctrineobject is not serialized
You can configure how the serialization is done by using annotations in the entity class. See the documentation in the link above. For example, here's how you would exclude linked entities:
/**
* Iddp\RorBundle\Entity\Report
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Iddp\RorBundle\Entity\ReportRepository")
* @ExclusionPolicy("None")
*/
....
/**
* @ORM\ManyToOne(targetEntity="Client", inversedBy="reports")
* @ORM\JoinColumn(name="client_id", referencedColumnName="id")
* @Exclude
*/
protected $client;
You should follow the guidelines on Add a secondary horizontal axis:
To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.
Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Layout tab, in the Axes group, click Axes.
Click Secondary Horizontal Axis, and then click the display option that you want.
You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.
In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:
Click the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.
On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.
Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.
On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.
A secondary vertical axis is displayed in the chart.
To change the display of the secondary vertical axis, do the following:
On the Layout tab, in the Axes group, click Axes.
Click Secondary Vertical Axis, and then click the display option that you want.
To change the axis options of the secondary vertical axis, do the following:
Right-click the secondary vertical axis, and then click Format Axis.
Under Axis Options, select the options that you want to use.
Could you use jQuery, since it's cross-browser compatible?
function isOnScreen(element)
{
var curPos = element.offset();
var curTop = curPos.top;
var screenHeight = $(window).height();
return (curTop > screenHeight) ? false : true;
}
And then call the function using something like:
if(isOnScreen($('#myDivId'))) { /* Code here... */ };
Replace the * with a /
So instead of
COPY * <destination>
use
COPY / <destination>
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
Depends on what you see as false in a string.
Empty string, the word false, 0, should all those be false or is only empty false or only the word false.
You probably need to buid your own method to test the string and return true or false to be 100 % sure that it does what you need.
You need to link with the math library:
gcc -o sphere sphere.c -lm
The error you are seeing: error: ld returned 1 exit status
is from the linker ld
(part of gcc that combines the object files) because it is unable to find where the function pow
is defined.
Including math.h
brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a
. You need to link your program with this library so that the calls to functions like pow() are resolved.
#!/bin/bash
cat <<EOF > SampleFile
Put Some text here
Put some text here
Put some text here
EOF
If I am understanding well, if what you want to do is to export dependencies during the compilation phase so there will be no need to retrieve manually each needed libraries, you can use the mojo copy-dependencies.
Hope it can be useful in your case (examples)
remove the ios::binary
from your modes in your ofstream and use studentPassword.c_str()
instead of (char *)&studentPassword
in your write.write()
If you go to Windows, Preferences then select General, Editors, Text editors, you can set colors on that property page (and there's a link for setting MORE colors - General, Appearance, Colors and fonts).
That's with an Eclipse 3.3 build anyway.
Boolean
types can be null
. You need to do a null
check as you have set it to null
.
if (bool != null && bool)
{
//DoSomething
}
If you're passing a value, however, things are different. You can force a value to be passed by reference. This allows you to pass an integer to a method, for example, and have the method modify the integer on your behalf.
is null
can be used to check whether null
data is coming from a query as in following example:
declare @Mem varchar(20),@flag int
select @mem=MemberClub from [dbo].[UserMaster] where UserID=@uid
if(@Mem is null)
begin
set @flag= 0;
end
else
begin
set @flag=1;
end
return @flag;
Two Solutions:
Try this code. This seems working in my case.
$this->db->where(array('id !='=> $id))
Although this is an older question, I thought I'd contribute something summing up what I think were the best of the other answers and add a wrinkle of my own by suggesting that you put these command(s) into a file and set your PYTHONSTARTUP environment variable to point to it. Since I'm on Windows at the moment, it's slightly biased that way, but could easily be slanted some other direction.
Here's some articles I found that describe how to set environment variables on Windows:
When to use sys.path.append and when modifying %PYTHONPATH% is enough
How To Manage Environment Variables in Windows XP
Configuring System and User Environment Variables
How to Use Global System Environment Variables in Windows
BTW, don't put quotes around the path to the file even if it has spaces in it.
Anyway, here's my take on the code to put in (or add to your existing) Python startup script:
# ==== pythonstartup.py ====
# add something to clear the screen
class cls(object):
def __repr__(self):
import os
os.system('cls' if os.name == 'nt' else 'clear')
return ''
cls = cls()
# ==== end pythonstartup.py ====
BTW, you can also use @Triptych's __repr__
trick to change exit()
into just exit
(and ditto for its alias quit
):
class exit(object):
exit = exit # original object
def __repr__(self):
self.exit() # call original
return ''
quit = exit = exit()
Lastly, here's something else that changes the primary interpreter prompt from >>>
to cwd+>>>
:
class Prompt:
def __str__(self):
import os
return '%s >>> ' % os.getcwd()
import sys
sys.ps1 = Prompt()
del sys
del Prompt
The Java XML parser that spring uses will read the schemaLocation
values and try to load them from the internet, in order to validate the XML file. Spring, in turn, intercepts those load requests and serves up versions from inside its own JAR files.
If you omit the schemaLocation
, then the XML parser won't know where to get the schema in order to validate the config.
There WHERE
part could be written like this:
WHERE
(LEN('TestPerson') <> 0 OR co.personentered = co.personentered) AND
(LEN('TestPerson') = 0 OR co.personentered LIKE '%TestPerson') AND
(cc.ccnum = CASE LEN('TestFFNum')
WHEN 0 THEN cc.ccnum
ELSE 'TestFFNum'
END ) AND
(LEN('2011-01-09 11:56:29.327') <> 0 OR co.DTEntered = co.DTEntered ) AND
((LEN('2011-01-09 11:56:29.327') = 0 AND LEN('2012-01-09 11:56:29.327') <> 0) OR co.DTEntered >= '2011-01-09 11:56:29.327' ) AND
((LEN('2011-01-09 11:56:29.327') = 0 AND LEN('2012-01-09 11:56:29.327') = 0) OR co.DTEntered BETWEEN '2011-01-09 11:56:29.327' AND '2012-01-09 11:56:29.327' ) AND
tl.storenum < 699
If you want to make it controller specific, you can use:
res.setHeader('X-Frame-Options', 'ALLOWALL');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
Please note that this will also allow iframes.
It took me quite a while to figure out, how to not get a false
when using openssl_decrypt()
and get encrypt and decrypt working.
// cryptographic key of a binary string 16 bytes long (because AES-128 has a key size of 16 bytes)
$encryption_key = '58adf8c78efef9570c447295008e2e6e'; // example
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted = openssl_encrypt($plaintext, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);
$encrypted = $encrypted . ':' . base64_encode($iv);
// decrypt to get again $plaintext
$parts = explode(':', $encrypted);
$decrypted = openssl_decrypt($parts[0], 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, base64_decode($parts[1]));
If you want to pass the encrypted string via a URL, you need to urlencode the string:
$encrypted = urlencode($encrypted);
To better understand what is going on, read:
To generate 16 bytes long keys you can use:
$bytes = openssl_random_pseudo_bytes(16);
$hex = bin2hex($bytes);
To see error messages of openssl you can use: echo openssl_error_string();
Hope that helps.
I needed a solution to select the previous sibling tr. I came up with this solution using React and Styled-components. This is not my exact solution (This is from memory, hours later). I know there is a flaw in the setHighlighterRow function.
OnMouseOver a row will set the row index to state, and rerender the previous row with a new background color
class ReactClass extends Component {
constructor() {
this.state = {
highlightRowIndex: null
}
}
setHighlightedRow = (index) => {
const highlightRowIndex = index === null ? null : index - 1;
this.setState({highlightRowIndex});
}
render() {
return (
<Table>
<Tbody>
{arr.map((row, index) => {
const isHighlighted = index === this.state.highlightRowIndex
return {
<Trow
isHighlighted={isHighlighted}
onMouseOver={() => this.setHighlightedRow(index)}
onMouseOut={() => this.setHighlightedRow(null)}
>
...
</Trow>
}
})}
</Tbody>
</Table>
)
}
}
const Trow = styled.tr`
& td {
background-color: ${p => p.isHighlighted ? 'red' : 'white'};
}
&:hover {
background-color: red;
}
`;
you just have to add this.
public int getActionBarHeight() {
int height;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
height = getActivity().getActionBar().getHeight();
} else {
height = ((ActionBarActivity) getActivity()).getSupportActionBar().getHeight();
}
return height;
}
MS-Access doesn't support ROW_NUMBER(). Use TOP 1:
SELECT TOP 1 *
FROM [MyTable]
ORDER BY [MyIdentityCOlumn]
If you need the 15th row - MS-Access has no simple, built-in, way to do this. You can simulate the rownumber by using reverse nested ordering to get this:
SELECT TOP 1 *
FROM (
SELECT TOP 15 *
FROM [MyTable]
ORDER BY [MyIdentityColumn] ) t
ORDER BY [MyIdentityColumn] DESC
It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:
To add columns in existing table:
ALTER TABLE table_name
ADD
column_name DATATYPE NULL
To delete columns in existing table:
ALTER TABLE table_name
DROP COLUMN column_name
public string ToString(this string value)
{
if (value == null)
{
value = string.Empty;
}
else
{
return value.Trim();
}
}
Here's the most important part from the lecture notes of CS299 (by Andrew Ng) related to the topic, which really helps me understand the difference between discriminative and generative learning algorithms.
Suppose we have two classes of animals, elephant (y = 1
) and dog (y = 0
). And x is the feature vector of the animals.
Given a training set, an algorithm like logistic regression or the perceptron algorithm (basically) tries to find a straight line — that is, a decision boundary — that separates the elephants and dogs. Then, to classify a new animal as either an elephant or a dog, it checks on which side of the decision boundary it falls, and makes its prediction accordingly. We call these discriminative learning algorithm.
Here's a different approach. First, looking at elephants, we can build a model of what elephants look like. Then, looking at dogs, we can build a separate model of what dogs look like. Finally, to classify a new animal, we can match the new animal against the elephant model, and match it against the dog model, to see whether the new animal looks more like the elephants or more like the dogs we had seen in the training set. We call these generative learning algorithm.
this is the source code about wraps:
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function
wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
for attr in assigned:
setattr(wrapper, attr, getattr(wrapped, attr))
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Return the wrapper so this can be used as a decorator via partial()
return wrapper
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
This is what worked for me.. All the other solutions didn't quite work for me, but I understood one thing from the other solutions and its that default styles of textarea
and label
in combination is responsible for the blue border.
textarea, label
{
outline:0px !important;
-webkit-box-shadow: none !important;
}
EDIT: I had this issue with Ant Design textarea. Thats why this solution worked for me. So, if you are using Ant, then use this.
Determine if 2 lists have the same elements, regardless of order?
Inferring from your example:
x = ['a', 'b']
y = ['b', 'a']
that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are), the most direct and computationally efficient answer uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school).
set(x) == set(y) # prefer this if elements are hashable
In the case that the elements are hashable, but non-unique, the collections.Counter
also works semantically as a multiset, but it is far slower:
from collections import Counter
Counter(x) == Counter(y)
Prefer to use sorted
:
sorted(x) == sorted(y)
if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.
An empirical experiment concludes that one should prefer set
, then sorted
. Only opt for Counter
if you need other things like counts or further usage as a multiset.
First setup:
import timeit
import random
from collections import Counter
data = [str(random.randint(0, 100000)) for i in xrange(100)]
data2 = data[:] # copy the list into a new one
def sets_equal():
return set(data) == set(data2)
def counters_equal():
return Counter(data) == Counter(data2)
def sorted_lists_equal():
return sorted(data) == sorted(data2)
And testing:
>>> min(timeit.repeat(sets_equal))
13.976069927215576
>>> min(timeit.repeat(counters_equal))
73.17287588119507
>>> min(timeit.repeat(sorted_lists_equal))
36.177085876464844
So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.
free
is not enough, free
just marks the memory as unused, the struct data will be there until overwriting. For safety, set the pointer to NULL
after free
.
Ex:
if (testPerson) {
free(testPerson);
testPerson = NULL;
}
struct
is similar like an array, it is a block of memory. You can access to struct member via its offset. The first struct's member is placed at offset 0
so the address of first struct's member is same as the address of struct.
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
Long.toString()
The following should work:
long myLong = 1234567890123L;
String myString = Long.toString(myLong);
Changing the type
of an <input type=password>
throws a security error in some browsers (old IE and Firefox versions).
You’ll need to create a new input
element, set its type
to the one you want, and clone all other properties from the existing one.
I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84
To work in Internet Explorer:
The function below accomplishes the above tasks for you:
<script>
function changeInputType(oldObject, oType) {
var newObject = document.createElement('input');
newObject.type = oType;
if(oldObject.size) newObject.size = oldObject.size;
if(oldObject.value) newObject.value = oldObject.value;
if(oldObject.name) newObject.name = oldObject.name;
if(oldObject.id) newObject.id = oldObject.id;
if(oldObject.className) newObject.className = oldObject.className;
oldObject.parentNode.replaceChild(newObject,oldObject);
return newObject;
}
</script>
Should be also noted that there might be problems in IE<=9 when using script defer
in certain situations. More on this: https://github.com/h5bp/lazyweb-requests/issues/42
I don't know if there's a way to get a clean build via the UI, but it's easy to do from the commandline using gradle wrapper. From the root directory of your project:
./gradlew clean
Update for PHP 7 (thanks shock_gone_wild)
PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:
$var = $var ?? "default";
Before PHP 7
No, there is no special operator or special syntax for this. However, you could use the ternary operator:
$var = isset($var) ? $var : "default";
Or like this:
isset($var) ?: $var = 'default';
Note, the localhost is a special string that FB allows here. If you didn't configure your debugging environment under localhost, you'll have to push it underneath that name as far as I can tell.
Note: if you were on Branch1
, you will with Git 2.0 (Q2 2014) be able to type:
git checkout Branch2
git rebase -
See commit 4f40740 by Brian Gesiak modocache
:
rebase
: allow "-
" short-hand for the previous branchTeach rebase the same shorthand as
checkout
andmerge
to name the branch torebase
the current branch on; that is, that "-
" means "the branch we were previously on".
You can also just do this:
<svg viewBox="0 0 32 32">
<path d="M11.333 13.173c0-2.51 2.185-4.506 4.794-4.506 2.67 0 4.539 2.053 4.539 4.506 0 2.111-0.928 3.879-3.836 4.392v0.628c0 0.628-0.496 1.141-1.163 1.141s-1.163-0.513-1.163-1.141v-1.654c0-0.628 0.751-1.141 1.419-1.141 1.335 0 2.571-1.027 2.571-2.224 0-1.255-1.092-2.224-2.367-2.224-1.335 0-2.367 1.027-2.367 2.224 0 0.628-0.546 1.141-1.214 1.141s-1.214-0.513-1.214-1.141zM15.333 23.333c-0.347 0-0.679-0.143-0.936-0.404s-0.398-0.597-0.398-0.949 0.141-0.689 0.398-0.949c0.481-0.488 1.39-0.488 1.871 0 0.257 0.26 0.398 0.597 0.398 0.949s-0.141 0.689-0.398 0.949c-0.256 0.26-0.588 0.404-0.935 0.404zM16 26.951c-6.040 0-10.951-4.911-10.951-10.951s4.911-10.951 10.951-10.951c6.040 0 10.951 4.911 10.951 10.951s-4.911 10.951-10.951 10.951zM16 3.333c-6.984 0-12.667 5.683-12.667 12.667s5.683 12.667 12.667 12.667c6.984 0 12.667-5.683 12.667-12.667s-5.683-12.667-12.667-12.667z"></path>
</svg>
_x000D_
Try this:
List<string> names = new List<string>("Tom,Scott,Bob".Split(','));
names.Reverse();
If nearly everything seems right, another thing to look out for is to ensure that the validation summary is not being explicitly hidden via some CSS override like this:
.validation-summary-valid {
display: none;
}
This may also cause the @Html.ValidationSummary
to appear hidden, as the summary is dynamically rendered with the validation-summary-valid
class.
in Global.asax add
public override void Init()
{
this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(
SessionStateBehavior.Required);
}
give it a shot ;)
Rails 3.0.9
select options_for_select([value1, value2, value3], default)
Not sure of the exact question but is this what you are looking for?
public class TestRun
{
public static void main(String [] args)
{
Map<String, Integer[]> prices = new HashMap<String, Integer[]>();
prices.put("milk", new Integer[] {1, 3, 2});
prices.put("eggs", new Integer[] {1, 1, 2});
}
}
The error of "Some data has already been output, can't send PDF file" refers to the output buffer of PHP.
so you need to clean any content of the output buffer before sending output.
ob_end_clean(); // Clean any content of the output buffer
then
$pdf->Output('example_001.pdf', 'I'); // Send the PDF !
More points regarding File Descriptor
:
File Descriptors
(FD) are non-negative integers (0, 1, 2, ...)
that are associated with files that are opened.
0, 1, 2
are standard FD's that corresponds to STDIN_FILENO
, STDOUT_FILENO
and STDERR_FILENO
(defined in unistd.h
) opened by default on behalf of shell when the program starts.
FD's are allocated in the sequential order, meaning the lowest possible unallocated integer value.
FD's for a particular process can be seen in /proc/$pid/fd
(on Unix based systems).
Robocopy can be downloaded here for systems where it is not installed already. (I.e. Windows Server 2003.)
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=17657 (no reboot required for installation)
Remember to set your path to the robocopy exe. You do this by right clicking "my computer"> properties>advanced>"Environment Variables", then find the path system variable and add this to the end: ";C:\Program Files\Windows Resource Kits\Tools" or wherever you installed it. Make sure to leave the path variable strings that are already there and just append the addtional path.
once the path is set, you can run the command that belisarius suggests. It works great.
how to determine if a commit with particular hash have been pushed to the origin already?
# list remote branches that contain $commit
git branch -r --contains $commit
I'm not sure it's possible "out of the box". And, unfortunately, I don't know an appropriate plugin either. To solve the problem you suggested you could use regular expressions.
[^ ]+
(or \d+
, or whatever you prefer)Hotkeys may vary depending on you OS and personal preferences (mine are for OS X).
You can try to provide your own thread factory, which will create thread with appropriate names. Here's one example:
class YourThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
return new Thread(r, "Your name");
}
}
Executors.newSingleThreadExecutor(new YourThreadFactory()).submit(someRunnable);
You can push current branch with command
git push origin HEAD
(took from here)
Once try by replacing localhost to your 'computer name' i.e, http://localhost:8080
to http://system09:8080
I dissent from both the answers. Don't create a reference at all, but use late binding:
Dim objExcelApp As Object
Dim wb As Object
Sub Initialize()
Set objExcelApp = CreateObject("Excel.Application")
End Sub
Sub ProcessDataWorkbook()
Set wb = objExcelApp.Workbooks.Open("path to my workbook")
Dim ws As Object
Set ws = wb.Sheets(1)
ws.Cells(1, 1).Value = "Hello"
ws.Cells(1, 2).Value = "World"
'Close the workbook
wb.Close
Set wb = Nothing
End Sub
You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().
This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.
Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.
Checkout CefSharp .Net bindings, a project I started a while back that thankfully got picked up by the community and turned into something wonderful.
The project wraps the Chromium Embedded Framework and has been used in a number of major projects including Rdio's Windows client, Facebook Messenger for Windows and Github for Windows.
It features browser controls for WPF and Winforms and has tons of features and extension points. Being based on Chromium it's blisteringly fast too.
Grab it from NuGet: Install-Package CefSharp.Wpf
or Install-Package CefSharp.WinForms
Check out examples and give your thoughts/feedback/pull-requests: https://github.com/cefsharp/CefSharp
BSD Licensed
Brian Goetz's "Java Concurrency In Practice" book, section 13.3: "...Like the default ReentrantLock, intrinsic locking offers no deterministic fairness guarantees, but the statistical fairness guarantees of most locking implementations are good enough for almost all situations..."
Try to use a grayscale colormap?
E.g. something like
imshow(..., cmap=pyplot.cm.binary)
For a list of colormaps, see http://scipy-cookbook.readthedocs.org/items/Matplotlib_Show_colormaps.html
$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();
The last one will fire the click event for the checkbox, the others will not. So if you have custom code in the onclick event for the checkbox that you want to fire, use the last one.
Use splatting.
$CurlArgument = '-u', '[email protected]:yyyy',
'-X', 'POST',
'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
'--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument
It's simple and my favorite.
<hr style="background-color: #dd3333" />
spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.
Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE
so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.
also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.
.cell-row {display: table; width: 100%; height: 100px; background-color: lightgrey; text-align: center}_x000D_
.cell {display: table-cell}_x000D_
.cell-middle {vertical-align: middle}
_x000D_
<div class="cell-row">_x000D_
<div class="cell cell-middle">Center</div>_x000D_
</div>
_x000D_
This is the only thing that worked for me:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
export default class Comp extends Component {
find_dimesions(layout){
const {x, y, width, height} = layout;
console.warn(x);
console.warn(y);
console.warn(width);
console.warn(height);
}
render() {
return (
<View onLayout={(event) => { this.find_dimesions(event.nativeEvent.layout) }} style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('Comp', () => Comp);
Count all td in table1:
console.log(_x000D_
table1.querySelectorAll("td").length_x000D_
)
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
Count all td into each tr of table1.
table1.querySelectorAll("tr").forEach(function(e){_x000D_
console.log( e.querySelectorAll("td").length )_x000D_
})
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
Whenever I have to do something like this I just become root:
# sudo -s
# ls -hal /root/ > /root/test.out
# exit
It's probably not the best way, but it works.
I agree with Jon about having a hash of actions to class name. If you keep your pattern, you might want to consider using the "as" construct instead:
A a = o as A;
if (a != null) {
a.Hop();
return;
}
B b = o as B;
if (b != null) {
b.Skip();
return;
}
throw new ArgumentException("...");
The difference is that when you use the patter if (foo is Bar) { ((Bar)foo).Action(); } you're doing the type casting twice. Now maybe the compiler will optimize and only do that work once - but I wouldn't count on it.
<input name="Name" value="Enter Your Name" onfocus="freez(this)" onblur="freez(this)">
function freez(obj)
{
if(obj.value=='')
{
obj.value='Enter Your Name';
}else if(obj.value=='Enter Your Name')
{
obj.value='';
}
}
I needed to do the same and had to query a query to get the result
I set my first query up to bring in all IDs from the table and all other information needed to filter:
SELECT tMAIN.tLOTS.NoContract, tMAIN.ID
FROM tMAIN INNER JOIN tLOTS ON tMAIN.ID = tLOTS.id
WHERE (((tLOTS.NoContract)=False));
Save this as Q04_1 -0 this returned 1229 results (there are 63 unique records to query - soime with multiple LOTs)
SELECT DISTINCT ID
FROM q04_1;
Saved that as q04_2
I then wrote another query which brought in the required information linked to the ID
SELECT q04_2.ID, tMAIN.Customer, tMAIN.Category
FROM q04_2 INNER JOIN tMAIN ON q04_2.ID = tMAIN.ID;
Worked a treat and got me exactly what I needed - 63 unique records returned with customer and category details.
This is how I worked around it as I couldn't get the Group By working at all - although I am rather "wet behind the ears" weith SQL (so please be gentle and constructive with feedback)
I would like to give another example in which multiple (3) joins are used.
DataClasses1DataContext ctx = new DataClasses1DataContext();
var Owners = ctx.OwnerMasters;
var Category = ctx.CategoryMasters;
var Status = ctx.StatusMasters;
var Tasks = ctx.TaskMasters;
var xyz = from t in Tasks
join c in Category
on t.TaskCategory equals c.CategoryID
join s in Status
on t.TaskStatus equals s.StatusID
join o in Owners
on t.TaskOwner equals o.OwnerID
select new
{
t.TaskID,
t.TaskShortDescription,
c.CategoryName,
s.StatusName,
o.OwnerName
};
Late answer, but I figured I should add a link to my site because I have written a tutorial how to make an image cache for android: http://squarewolf.nl/2010/11/android-image-cache/ Update: the page has been taken offline as the source was outdated. I join @elenasys in her advice to use Ignition.
So to all the people who stumble upon this question and haven't found a solution: hope you enjoy! =D
You cannot use the VB line-continuation character inside of a string.
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value & _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"
Just don't use <object>
. Here's a solution that worked for me with <a>
and <svg>
tags:
<a href="<your-link>" class="mr-5 p-1 border-2 border-transparent text-gray-400 rounded-full hover:text-white focus:outline-none focus:text-white focus:bg-red-700 transition duration-150 ease-in-out" aria-label="Notifications">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="30"
height="30"><path class="heroicon-ui" fill="#fff" d="M17 16a3 3 0 1 1-2.83
2H9.83a3 3 0 1 1-5.62-.1A3 3 0 0 1 5 12V4H3a1 1 0 1 1 0-2h3a1 1 0 0 1 1
1v1h14a1 1 0 0 1 .9 1.45l-4 8a1 1 0 0 1-.9.55H5a1 1 0 0 0 0 2h12zM7 12h9.38l3-
6H7v6zm0 8a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm10 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"/>
</svg>
</a>
You have two options, and I'll leave selection up to you.
Shared Preferences
This is a framework unique to Android that allows you to store primitive values (such as int
, boolean,
and String
, although strictly speaking String
isn't a primitive) in a key-value framework. This means that you give a value a name, say, "homeScore" and store the value to this key.
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("homeScore", YOUR_HOME_SCORE);
// Apply the edits!
editor.apply();
// Get from the SharedPreferences
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
int homeScore = settings.getInt("homeScore", 0);
Internal Storage
This, in my opinion, is what you might be looking for. You can store anything you want to a file, so this gives you more flexibility. However, the process can be trickier because everything will be stored as bytes, and that means you have to be careful to keep your read and write processes working together.
int homeScore;
byte[] homeScoreBytes;
homeScoreBytes[0] = (byte) homeScore;
homeScoreBytes[1] = (byte) (homeScore >> 8); //you can probably skip these two
homeScoreBytes[2] = (byte) (homeScore >> 16); //lines, because I've never seen a
//basketball score above 128, it's
//such a rare occurance.
FileOutputStream outputStream = getApplicationContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);
outputStream.write(homeScoreBytes);
outputStream.close();
Now, you can also look into External Storage, but I don't recommend that in this particular case, because the external storage might not be there later. (Note that if you pick this, it requires a permission)
If you use the Angular CLI to create your components, let's say CarComponent
, it attaches app
to the selector name (i.e app-car
) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car>
or change the selector in the CarComponent
to selector: 'car'
I did not have the issue when developing in localhost. However, once I published to a web server, the webservice was returning an empty (blank) result and I was seeing the error in my logs.
I fixed it by setting my ajax contentType to :
"application/json; charset=utf-8"
and using :
JSON.stringify()
on the object I was posting.
var postData = {data: myData};
$.ajax({
type: "POST",
url: "../MyService.asmx/MyMethod",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
dataType: "json"
});
Here is a nice widget/plugin library which has ellipsis built in: http://www.codeitbetter.co.uk/widgets/ellipsis/ All you need to do it reference the library and call the following:
<script type="text/javascript">
$(document).ready(function () {
$(".ellipsis_10").Ellipsis({
numberOfCharacters: 10,
showLessText: "less",
showMoreText: "more"
});
});
</script>
<div class="ellipsis_10">
Some text here that's longer than 10 characters.
</div>
It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,
if (window.variableName)
is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.
That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.
if ( variableName && typeof variableName !== 'undefined' )
The easiest way to change the background color of the jumbotron
If you want to change the background color of your jumbotron, then for that you can apply a background color to it using one of your custom class.
HTML Code:
<div class="jumbotron myclass">
<h1>My Heading</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>
CSS Code:
<style>
.myclass{
background-color: red;
}
</style>
Problem was apparently not the SQL server, but the NAV system that updates the field. There is a compression property that can be used on BLOB fields in NAV, that is not a part of SQL Server. So the custom compression made the data unreadable, though the conversion worked.
The solution was to turn off compression through the Object Designer, Table Designer, Properties for the field (Shift+F4 on the field row).
After that the extraction of data can be made with e.g.: select convert(varchar(max), cast(BLOBFIELD as binary)) from Table
Thanks for all answers that were correct in many ways!
Add maven directory /bin
to System variables under the name Path
.
To check this, you can echo %PATH%
Same issue for me... Upload app archives from Xcode (7.3.1). Connect to iTunesCo with both Chrome and Safari...
The way it works has no logic... So I agree with @teapen:
...don't wait for Apple, just increase build and upload again...
Here's a batch script I made to return a timestamp. An optional first argument may be provided to be used as a field delimiter. For example:
c:\sys\tmp>timestamp.bat
20160404_144741
c:\sys\tmp>timestamp.bat -
2016-04-04_14-45-25
c:\sys\tmp>timestamp.bat :
2016:04:04_14:45:29
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
:: put your desired field delimiter here.
:: for example, setting DELIMITER to a hyphen will separate fields like so:
:: yyyy-MM-dd_hh-mm-ss
::
:: setting DELIMITER to nothing will output like so:
:: yyyyMMdd_hhmmss
::
SET DELIMITER=%1
SET DATESTRING=%date:~-4,4%%DELIMITER%%date:~-7,2%%DELIMITER%%date:~-10,2%
SET TIMESTRING=%TIME%
::TRIM OFF the LAST 3 characters of TIMESTRING, which is the decimal point and hundredths of a second
set TIMESTRING=%TIMESTRING:~0,-3%
:: Replace colons from TIMESTRING with DELIMITER
SET TIMESTRING=%TIMESTRING::=!DELIMITER!%
:: if there is a preceeding space substitute with a zero
echo %DATESTRING%_%TIMESTRING: =0%
What does it mean?
It means that you should not try to use the same iterator in two threads. If you have two threads that need to iterate over the keys, values or entries, then they each should create and use their own iterators.
What happens if I try to iterate the map with two threads at the same time?
It is not entirely clear what would happen if you broke this rule. You could just get confusing behavior, in the same way that you do if (for example) two threads try to read from standard input without synchronizing. You could also get non-thread-safe behavior.
But if the two threads used different iterators, you should be fine.
What happens if I put or remove a value from the map while iterating it?
That's a separate issue, but the javadoc section that you quoted adequately answers it. Basically, the iterators are thread-safe, but it is not defined whether you will see the effects of any concurrent insertions, updates or deletions reflected in the sequence of objects returned by the iterator. In practice, it probably depends on where in the map the updates occur.
(<HTMLInputElement>document.getElementById('loginInput')).value = '123';
Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.
UPDATE::
This can also be done using ViewChild with #localvariable as shown here, as mentioned in here
<textarea #someVar id="tasknote"
name="tasknote"
[(ngModel)]="taskNote"
placeholder="{{ notePlaceholder }}"
style="background-color: pink"
(blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }}
</textarea>
import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;
constructor(private rd: Renderer2) {}
ngAfterViewInit() {
console.log(this.rd);
this.el.nativeElement.focus(); //<<<=====same as oldest way
}
select a.ip, a.os, a.hostname, a.port, a.protocol,
b.state
from a
left join b on a.ip = b.ip
and a.port = b.port
Interesting question - I don't think there's any Oracle function that does this (almost like a "which" command in Unix), but you can get the resolution order for the name by:
select * from
(
select object_name objname, object_type, 'my object' details, 1 resolveOrder
from user_objects
where object_type not like 'SYNONYM'
union all
select synonym_name obj , 'my synonym', table_owner||'.'||table_name, 2 resolveOrder
from user_synonyms
union all
select synonym_name obj , 'public synonym', table_owner||'.'||table_name, 3 resolveOrder
from all_synonyms where owner = 'PUBLIC'
)
where objname like upper('&objOfInterest')
I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter
:
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
_x000D_
var found = arr.filter(function(item) { return item.name === 'k1'; });_x000D_
_x000D_
console.log('found', found[0]);
_x000D_
Check the console.
_x000D_
You can see a list of supported browsers here.
In the future with ES6, you'll be able to use array.find.
If there is any error at all in the PATH windows will silently disregard it. Things like having %PATH% or spaces between items in your path will break it. Be warned
Please check this answer
// In angularJS script
$scope.foo = function() {
console.log('test');
};
$window.angFoo = function() {
$scope.foo();
$scope.$apply();
};
// In jQuery
if (window.angFoo) {
window.angFoo();
}
In SQL Server 2012, 2014:
USE mydb
GO
ALTER ROLE db_datareader ADD MEMBER MYUSER
GO
ALTER ROLE db_datawriter ADD MEMBER MYUSER
GO
In SQL Server 2008:
use mydb
go
exec sp_addrolemember db_datareader, MYUSER
go
exec sp_addrolemember db_datawriter, MYUSER
go
To also assign the ability to execute all Stored Procedures for a Database:
GRANT EXECUTE TO MYUSER;
To assign the ability to execute specific stored procedures:
GRANT EXECUTE ON dbo.sp_mystoredprocedure TO MYUSER;
A hack that's going to work with pretty much every possible browser is to use open classes like this: <a class='data\_articleid\_5' href="link/for/non-js-users.html>;
This is not all that elegant to the purists, but it's universally supported, standard-compliant, and very easy to manipulate. It really seems like the best possible method. If you serialize
, modify, copy your tags, or do pretty much anything else, data
will stay attached, copied etc.
The only problem is that you cannot store non-serializable objects that way, and there might be limits if you put something really huge there.
A second way is to use fake attributes like: <a articleid='5' href="link/for/non-js-users.html">
This is more elegant, but breaks standard, and I'm not 100% sure about support. Many browsers support it fully, I think IE6 supports JS
access for it but not CSS
selectors
(which doesn't really matter here), maybe some browsers will be completely confused, you need to check it.
Doing funny things like serializing and deserializing would be even more dangerous.
Using ids
to pure JS
hash mostly works, except when you try to copy your tags. If you have tag
<a href="..." id="link0">
, copy it via standard JS
methods, and then try to modify data
attached to just one copy, the other copy will be modified.
It's not a problem if you don't copy tag
s, or use read only data. If you copy tag
s and they're modified you'll need to handle that manually.
Below is the method that worked for me on API 23-25 emulators. The explanation is provided for API 24 but works almost identically for other versions.
Credits: Jon Doe, zaidorx, pjl.
Warm advice for readers: please just go over the steps before following them, as some are automated via provided scripts.
In the AVD manager of Android studio (tested on v2.2.3), create a new emulator with the "Android 7.0 (Google APIs)" target:
Download the latest Open GApps package for the emulator's architecture (CPU/ABI). In my case it was x86_64
, but it can be something else depending on your choice of image during the device creation wizard. Interestingly, the architecture seems more important than the correct Android version (i.e. gapps for 6.0 also work on a 7.0 emulator).
Extract the .apk
files using from the following paths (relative to open_gapps-x86_64-7.0-pico-201#####.zip
):
.zip\Core\gmscore-x86_64.tar.lz\gmscore-x86_64\nodpi\priv-app\PrebuiltGmsCore\
.zip\Core\gsfcore-all.tar.lz\gsfcore-all\nodpi\priv-app\GoogleServicesFramework\
.zip\Core\gsflogin-all.tar.lz\gsflogin-all\nodpi\priv-app\GoogleLoginService\
.zip\Core\vending-all.tar.lz\vending-all\nodpi\priv-app\Phonesky\
Note that Open GApps use the Lzip compression, which can be opened using either the tool found on the Lzip website1,2, or on Mac using homebrew: brew install lzip
. Then e.g. lzip -d gmscore-x86_64.tar.lz
.
I'm providing a batch file that utilizes 7z.exe
and lzip.exe
to extract all required .apk
s automatically (on Windows):
@echo off
echo.
echo #################################
echo Extracting Gapps...
echo #################################
7z x -y open_gapps-*.zip -oGAPPS
echo Extracting Lzips...
lzip -d GAPPS\Core\gmscore-x86_64.tar.lz
lzip -d GAPPS\Core\gsfcore-all.tar.lz
lzip -d GAPPS\Core\gsflogin-all.tar.lz
lzip -d GAPPS\Core\vending-all.tar.lz
move GAPPS\Core\*.tar
echo.
echo #################################
echo Extracting tars...
echo #################################
7z e -y -r *.tar *.apk
echo.
echo #################################
echo Cleaning up...
echo #################################
rmdir /S /Q GAPPS
del *.tar
echo.
echo #################################
echo All done! Press any key to close.
echo #################################
pause>nul
To use this, save the script in a file (e.g. unzip_gapps.bat
) and put everything relevant in one folder, as demonstrated below:
Update the su
binary to be able to modify the permissions of the files we will later upload. A new su
binary can be found in the SuperSU by Chainfire package "Recovery flashable" zip
. Get the zip, extract it somewhere, create the a batch file with the following contents in the same folder, and finally run it:
adb root
adb remount
adb push eu.chainfire.supersu_2.78.apk /system/app/
adb push x64/su /system/xbin/su
adb shell chmod 755 /system/xbin/su
adb shell ln -s /system/xbin/su /system/bin/su
adb shell "su --daemon &"
adb shell rm /system/app/SdkSetup.apk
Put all .apk
files in one folder and create a batch file with these contents3:
START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24 -no-boot-anim -writable-system
adb wait-for-device
adb root
adb shell stop
adb remount
adb push PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore
adb push GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework
adb push GoogleLoginService.apk /system/priv-app/GoogleLoginService
adb push Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
adb shell su root "chmod 777 /system/priv-app/**"
adb shell su root "chmod 777 /system/priv-app/PrebuiltGmsCore/*"
adb shell su root "chmod 777 /system/priv-app/GoogleServicesFramework/*"
adb shell su root "chmod 777 /system/priv-app/GoogleLoginService/*"
adb shell su root "chmod 777 /system/priv-app/Phonesky/*"
adb shell start
Notice that the path E:\...\android-sdk\tools\emulator.exe
should be modified according to the location of the Android SDK on your system.
Execute the above batch file (the console should look like this afterwards):
O:\123>START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24 -no-boot-anim -writable-system
O:\123>adb wait-for-device
Hax is enabled
Hax ram_size 0x60000000
HAX is working and emulator runs in fast virt mode.
emulator: Listening for console connections on port: 5554
emulator: Serial number of this emulator (for ADB): emulator-5554
O:\123>adb root
O:\123>adb shell stop
O:\123>adb remount
remount succeeded
O:\123>adb push PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore/
[100%] /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk
O:\123>adb push GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework/
[100%] /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk
O:\123>adb push GoogleLoginService.apk /system/priv-app/GoogleLoginService/
[100%] /system/priv-app/GoogleLoginService/GoogleLoginService.apk
O:\123>adb push Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
[100%] /system/priv-app/Phonesky/Phonesky.apk
O:\123>adb shell su root "chmod 777 /system/priv-app/**"
O:\123>adb shell su root "chmod 777 /system/priv-app/PrebuiltGmsCore/*"
O:\123>adb shell su root "chmod 777 /system/priv-app/GoogleServicesFramework/*"
O:\123>adb shell su root "chmod 777 /system/priv-app/GoogleLoginService/*"
O:\123>adb shell su root "chmod 777 /system/priv-app/Phonesky/*"
O:\123>adb shell start
When the emulator loads - close it, delete the Virtual Device and then create another one using the same system image. This fixes the unresponsive Play Store app, "Google Play Services has stopped" and similar problems. It works because in the earlier steps we have actually modified the system image itself (take a look at the Date modified on android-sdk\system-images\android-24\google_apis\x86_64\system.img
). This means that every device created from now on with the system image will have gapps installed!
Start the new AVD. If it takes unusually long to load, close it and instead start it using:
START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24
adb wait-for-device
adb shell "su --daemon &"
After the AVD starts you will see the image below - notice the Play Store icon in the corner!
3 - I'm not sure all of these commands are needed, and perhaps some of them are overkill... it seems to work - which is what counts. :)
According to the new Tensorflow version, tf.train.Checkpoint
is the preferable way of saving and restoring a model:
Checkpoint.save
andCheckpoint.restore
write and read object-based checkpoints, in contrast to tf.train.Saver which writes and reads variable.name based checkpoints. Object-based checkpointing saves a graph of dependencies between Python objects (Layers, Optimizers, Variables, etc.) with named edges, and this graph is used to match variables when restoring a checkpoint. It can be more robust to changes in the Python program, and helps to support restore-on-create for variables when executing eagerly. Prefertf.train.Checkpoint
overtf.train.Saver
for new code.
Here is an example:
import tensorflow as tf
import os
tf.enable_eager_execution()
checkpoint_directory = "/tmp/training_checkpoints"
checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt")
checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)
status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory))
for _ in range(num_training_steps):
optimizer.minimize( ... ) # Variables will be restored on creation.
status.assert_consumed() # Optional sanity checks.
checkpoint.save(file_prefix=checkpoint_prefix)
If you don't want to use a module you have to install like requests
, and your use case is very basic, then you can use urllib2
urllib2.urlopen(url, body)
See the documentation for urllib2
here: https://docs.python.org/2/library/urllib2.html.
I use a handy app called Karabiner to do this, and many other things. It's free and open source.
It's a keyboard remapper, with a lot of handy presets for many common remaps that people may want to do.
As you can see from the screenshot, this remap is included as a preset in Karabiner.
Hope this helps. Happy remapping!
If you assign its output to a variable, bash
automatically strips whitespace:
linecount=`wc -l < log.txt`
Okay, just to clarify things that have already been posted.
You should have the directory com
, containing the directory company
, containing the directory example
, containing the file MyClass.java
.
From the folder containing com
, run:
$ javac com\company\example\MyClass.java
Then:
$ java com.company.example.MyClass Hello from MyClass!
These must both be done from the root of the source tree. Otherwise, javac
and java
won't be able to find any other packages (in fact, java
wouldn't even be able to run MyClass
).
I created the folders "testpackage" and "testpackage2". Inside testpackage, I created TestPackageClass.java containing the following code:
package testpackage;
import testpackage2.MyClass;
public class TestPackageClass {
public static void main(String[] args) {
System.out.println("Hello from testpackage.TestPackageClass!");
System.out.println("Now accessing " + MyClass.NAME);
}
}
Inside testpackage2, I created MyClass.java containing the following code:
package testpackage2;
public class MyClass {
public static String NAME = "testpackage2.MyClass";
}
From the directory containing the two new folders, I ran:
C:\examples>javac testpackage\*.java C:\examples>javac testpackage2\*.java
Then:
C:\examples>java testpackage.TestPackageClass Hello from testpackage.TestPackageClass! Now accessing testpackage2.MyClass
Does that make things any clearer?
Change that import to
from matplotlib.pyplot import *
Note that this style of imports (from X import *
) is generally discouraged. I would recommend using the following instead:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
I had this problem when I installed MySQL 8.0.15 with the community installer. The my.ini file that came with the installer did not work correctly after it had been edited. I did a full manual install by downloading that zip folder. I was able to create my own my.ini file containing only the parameters that I was concerned about and it worked.
include the parameters in that my.ini file that you are concerned about. so something like this(just ensure that there is already a folder created for the datadir or else initialization won't work):
[mysqld]
basedire=C:\program files\MySQL\MySQL8.0
datadir=D:\MySQL\Data
....continue with whatever parameters you want to include
initialize the data directory by running these two commands in the command prompt:
cd C:\program files\MySQL\MySQL8.0\bin
mysqld --default-file=C:\program files\MySQL\MySQL8.0\my.ini --initialize
install the MySQL server as a service by running these two commands:
cd C:\program files\MySQL\MySQL8.0\bin
mysqld --install --default-file=C:\program files\MySQL\MySQL8.0\my.ini
finally, start the server for the first time by running these two commands:
cd C:\program files\MySQL\MySQL8.0\bin
mysqld --console
Here is an edited version of your code which is based on ISO C++ and which works well with G++:
#include <string.h>
#include <iostream>
using namespace std;
#define NO_OF_TEST 1
struct studentType {
string studentID;
string firstName;
string lastName;
string subjectName;
string courseGrade;
int arrayMarks[4];
double avgMarks;
};
studentType input() {
studentType newStudent;
cout << "\nPlease enter student information:\n";
cout << "\nFirst Name: ";
cin >> newStudent.firstName;
cout << "\nLast Name: ";
cin >> newStudent.lastName;
cout << "\nStudent ID: ";
cin >> newStudent.studentID;
cout << "\nSubject Name: ";
cin >> newStudent.subjectName;
for (int i = 0; i < NO_OF_TEST; i++) {
cout << "\nTest " << i+1 << " mark: ";
cin >> newStudent.arrayMarks[i];
}
return newStudent;
}
int main() {
studentType s;
s = input();
cout <<"\n========"<< endl << "Collected the details of "
<< s.firstName << endl;
return 0;
}
Try the outline property W3Schools - CSS Outline
Outline will not interfere with widths and lenghts of the elements/divs!
Please click the link I provided at the bottom to see working demos of the the different ways you can make borders, and inner/inline borders, even ones that do not disrupt the dimensions of the element! No need to add extra divs every time, as mentioned in another answer!
You can also combine borders with outlines, and if you like, box-shadows (also shown via link)
<head>
<style type="text/css" ref="stylesheet">
div {
width:22px;
height:22px;
outline:1px solid black;
}
</style>
</head>
<div>
outlined
</div>
Usually by default, 'border:' puts the border on the outside of the width, measurement, adding to the overall dimensions, unless you use the 'inset' value:
div {border: inset solid 1px black};
But 'outline:' is an extra border outside of the border, and of course still adds extra width/length to the element.
Hope this helps
PS: I also was inspired to make this for you : Using borders, outlines, and box-shadows
@Konrad what surprises me is that in my tests, I'm passing the list into a method that accepts IEnumerable<T>
, so the runtime can't optimize it by calling the Count() extension method for IList<T>
.
I can only assume that the Count() extension method for IEnumerable is doing something like this:
public static int Count<T>(this IEnumerable<T> list)
{
if (list is IList<T>) return ((IList<T>)list).Count;
int i = 0;
foreach (var t in list) i++;
return i;
}
... in other words, a bit of runtime optimization for the special case of IList<T>
.
/EDIT @Konrad +1 mate - you're right about it more likely being on ICollection<T>
.
Even if old, this seems to be a popular questions, so I'll post another solution, which I think is very elegant:
http://fiveminutelessons.com/learn-microsoft-excel/using-multiple-if-statements-excel
It's elegant because it uses just the IF function. Basically, it boils down to this:
if(condition, choose/use a value from the table, if(condition, choose/use another value from the table...
And so on
Works beautifully, even better than HLOOKUP or VLOOOKUP
but... Be warned - there is a limit to the number of nested if statements excel can handle.
Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:
SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a
If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.
@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
return jsonObject;
}
Got it. Its using the getApplicationInfo()
method of the Context
class.
r = 13 + 7.*rand(100,1);
Where 100,1 is the size of the desidered vector
Use repr
and eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
Note that eval
is not safe if the source of string is unknown, prefer ast.literal_eval
for safer conversion:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])
help on repr
:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.
I had the same issue, couldn't find a right solution so I have manually deleted the component folder and then updated the app.module.ts file (removed the references to the deleted component) and it worked for me.
As of PHP 7.1 you can simply do this:
$date = new DateTime( "NOW" );
echo $date->format( "m-d-Y H:i:s.u" );
It will display as:
04-11-2018 10:54:01.321688
Here is the batch file which should work for you:
@echo off
Title HOST: Installing updates on %computername%
echo %computername%
set Server=\\SERVERNAME or PATH\msifolder
:select
cls
echo Select one of the following MSI install folders for installation task.
echo.
dir "%Server%" /AD /ON /B
echo.
set /P "MSI=Please enter the MSI folder to install: "
set "Package=%Server%\%MSI%\%MSI%.msi"
if not exist "%Package%" (
echo.
echo The entered folder/MSI file does not exist ^(typing mistake^).
echo.
setlocal EnableDelayedExpansion
set /P "Retry=Try again [Y/N]: "
if /I "!Retry!"=="Y" endlocal & goto select
endlocal
goto :EOF
)
echo.
echo Selected installation: %MSI%
echo.
echo.
:verify
echo Is This Correct?
echo.
echo.
echo 0: ABORT INSTALL
echo 1: YES
echo 2: NO, RE-SELECT
echo.
set /p "choice=Select YES, NO or ABORT? [0,1,2]: "
if [%choice%]==[0] goto :EOF
if [%choice%]==[1] goto yes
goto select
:yes
echo.
echo Running %MSI% installation ...
start "Install MSI" /wait "%SystemRoot%\system32\msiexec.exe" /i /quiet "%Package%"
The characters listed on last page output on entering in a command prompt window either help cmd
or cmd /?
have special meanings in batch files. Here are used parentheses and square brackets also in strings where those characters should be interpreted literally. Therefore it is necessary to either enclose the string in double quotes or escape those characters with character ^
as it can be seen in code above, otherwise command line interpreter exits batch execution because of a syntax error.
And it is not possible to call a file with extension MSI. A *.msi file is not an executable. On double clicking on a MSI file, Windows looks in registry which application is associated with this file extension for opening action. And the application to use is msiexec
with the command line option /i
to install the application inside MSI package.
Run msiexec.exe /?
to get in a GUI window the available options or look at Msiexec (command-line options).
I have added already /quiet
additionally to required option /i
for a silent installation.
In batch code above command start
is used with option /wait
to start Windows application msiexec.exe
and hold execution of batch file until installation finished (or aborted).
replace {userid} and {password} with your id and password in your organization or login to your machine.
npm config set proxy http://{userid}:{password}@proxyip:8080/
npm config set https-proxy http://{userid}:{password}@proxyip:8080/
npm config set http-proxy http://{userid}:{password}@proxyip:8080/
strict-ssl=false
See this question for the why (taken from the comments).
If you really need to do something like this, you may want an abstract base class rather than an interface.
It looks like you might have inserted an extra +
at the beginning of each line, which R is interpreting as a unary operator (like -
interpreted as negation, rather than subtraction). I think what will work is
ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot() +
scale_fill_manual(values = c("yellow", "orange")) +
ggtitle("Expression comparisons for ACTB") +
theme(axis.text.x = element_text(angle=90, face="bold", colour="black"))
Perhaps you copy and pasted from the output of an R console? The console uses +
at the start of the line when the input is incomplete.
It is a build target that is not a filename.
This is the case you are using Julia:
The analogue of IPython's %matplotlib in Julia is to use the PyPlot package, which gives a Julia interface to Matplotlib including inline plots in IJulia notebooks. (The equivalent of numpy is already loaded by default in Julia.) Given PyPlot, the analogue of %matplotlib inline is using PyPlot, since PyPlot defaults to inline plots in IJulia.
I implemented a rooted tree as a dictionary {child:parent}
. So for instance with the root node 0
, a tree might look like that:
tree={1:0, 2:0, 3:1, 4:2, 5:3}
This structure made it quite easy to go upward along a path from any node to the root, which was relevant for the problem I was working on.
instead of using
ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);
try using
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
You can try with textContent.
var productId = val[key].textContent;
put public, protected or private before the $connection.
You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the cmap
object you have.
import matplotlib
cmap = matplotlib.cm.get_cmap('Spectral')
rgba = cmap(0.5)
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0)
For values outside of the range [0.0, 1.0] it will return the under and over colour (respectively). This, by default, is the minimum and maximum colour within the range (so 0.0 and 1.0). This default can be changed with cmap.set_under()
and cmap.set_over()
.
For "special" numbers such as np.nan
and np.inf
the default is to use the 0.0 value, this can be changed using cmap.set_bad()
similarly to under and over as above.
Finally it may be necessary for you to normalize your data such that it conforms to the range [0.0, 1.0]
. This can be done using matplotlib.colors.Normalize
simply as shown in the small example below where the arguments vmin
and vmax
describe what numbers should be mapped to 0.0 and 1.0 respectively.
import matplotlib
norm = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0)
print(norm(15.0)) # 0.5
A logarithmic normaliser (matplotlib.colors.LogNorm) is also available for data ranges with a large range of values.
(Thanks to both Joe Kington and tcaswell for suggestions on how to improve the answer.)
Even if your data falls within your specified limits (e.g. c(0, 335)
), adding a geom_jitter()
statement could push some points outside those limits, producing the same error message.
library(ggplot2)
range(mtcars$hp)
#> [1] 52 335
# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
scale_y_continuous(limits=c(0,335))
# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).
Created on 2020-08-24 by the reprex package (v0.3.0)
Use the in_array()
function.
$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');
if (in_array('kitchen', $array)) {
echo 'this array contains kitchen';
}
Besides what other said, a common problem is to declare the types of the same function that is overloaded. Typical case is EventEmitter on() method which will accept multiple kind of listeners. Similar could happen When working with redux actions - and there you use the action type as literal to mark the overloading, In case of EventEmitters, you use the event name literal type:
interface MyEmitter extends EventEmitter {
on(name:'click', l: ClickListener):void
on(name:'move', l: MoveListener):void
on(name:'die', l: DieListener):void
//and a generic one
on(name:string, l:(...a:any[])=>any):void
}
type ClickListener = (e:ClickEvent)=>void
type MoveListener = (e:MoveEvent)=>void
... etc
// will type check the correct listener when writing something like:
myEmitter.on('click', e=>...<--- autocompletion
Using .jpg files do not forget about compiling directly to .pdf (pdflatex) and use: graphicx package with pdftex option (\usepackage[pdftex]{graphicx}).
For me the fix was to install a newer version (1.24) of docker-compose
using this article.
The previous version (1.17) was installed from ubuntu
's default repository, but after installing a newer version I managed to launch the container. Hope it helps somebody.
Add this to .project file
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>framework</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>
What's wrong with self.left = None
?
you can try:
services:
nameis:
container_name: hi_my
build: .
image: hi_my_nameis:v1.0.0
This will probably solve your problem: https://help.ubuntu.com/community/EnvironmentVariables
Session-wide environment variables
In order to set environment variables in a way that affects a particular user's environment, one should not place commands to set their values in particular shell script files in the user's home directory, but use:
~/.pam_environment - This file is specifically meant for setting a user's environment. It is not a script file, but rather consists of assignment expressions, one per line.
Not recommended:
~/.profile - This is probably the best file for placing environment variable assignments in, since it gets executed automatically by the DisplayManager during the startup process desktop session as well as by the login shell when one logs-in from the textual console.
someClassWithinYourSourceDir.getClass().getResourceAsStream();
The latest version of sqlcmd adds the -w
option to remove extra space after the field value; however, it does not put quotes around strings, which can be a problem with CSV files when importing a field value that contains a comma.
You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean "has executed" check though if it is only supposed to run on the first activation.
You need to reduce an NP-Complete problem to the problem you have. If the reduction can be done in polynomial time then you have proven that your problem is NP-complete, if the problem is already in NP, because:
It is not easier than the NP-complete problem, since it can be reduced to it in polynomial time which makes the problem NP-Hard.
See the end of http://www.ics.uci.edu/~eppstein/161/960312.html for more.
There should be a container that maps component names to all components that are supposed to be used dynamically. Component classes should be registered in a container because in modular environment there's otherwise no single place where they could be accessed. Component classes cannot be identified by their names without specifying them explicitly because function name
is minified in production.
It can be plain object:
class Foo extends React.Component { ... }
...
const componentsMap = { Foo, Bar };
...
const componentName = 'Fo' + 'o';
const DynamicComponent = componentsMap[componentName];
<DynamicComponent/>;
Or Map
instance:
const componentsMap = new Map([[Foo, Foo], [Bar, Bar]]);
...
const DynamicComponent = componentsMap.get(componentName);
Plain object is more suitable because it benefits from property shorthand.
A barrel module with named exports can act as such map:
// Foo.js
export class Foo extends React.Component { ... }
// dynamic-components.js
export * from './Foo';
export * from './Bar';
// some module that uses dynamic component
import * as componentsMap from './dynamic-components';
const componentName = 'Fo' + 'o';
const DynamicComponent = componentsMap[componentName];
<DynamicComponent/>;
This works well with one class per module code style.
Decorators can be used with class components for syntactic sugar, this still requires to specify class names explicitly and register them in a map:
const componentsMap = {};
function dynamic(Component) {
if (!Component.displayName)
throw new Error('no name');
componentsMap[Component.displayName] = Component;
return Component;
}
...
@dynamic
class Foo extends React.Component {
static displayName = 'Foo'
...
}
A decorator can be used as higher-order component with functional components:
const Bar = props => ...;
Bar.displayName = 'Bar';
export default dynamic(Bar);
The use of non-standard displayName
instead of random property also benefits debugging.
I have made a jsfiddle for you.
<canvas id="canvas" width="480" height="320"></canvas>
<button id="download">Download Pdf</button>
'
html2canvas($("#canvas"), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
}
});
jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/
Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.
ALTER TABLE table_name
MODIFY (column_name data_type);
You can do it this way:
=IF(E9>21,"Text 1",IF(AND(E9>=5,E9<=21),"Test 2","Text 3"))
Note I assume you meant >=
and <=
here since your description skipped the values 5
and 21
, but you can adjust these inequalities as needed.
Or you can do it this way:
=IF(E9>21,"Text 1",IF(E9<5,"Text 3","Text 2"))
Be sure to check Xcode Preferences -> Locations.
The Command Line Tools I had selected was for the previous version of Xcode (8.2.1 instead of 10.1)
Execute: sudo gedit ~/.bashrc
add
JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export JAVA_HOME
PATH=$PATH:$JAVA_HOME
export PATH
export ANDROID_HOME=~/Android/Sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
and
source ~/.bashrc
ok just so you know there is a program out there that's called DroidDraw. It can help you draw objects and try them one on top of the other. I tried your solution but I had animation under the smaller image so that didn't work. But then I tried to place one image in a relative layout that's suppose to be under first and then on top of that I drew the other image that is suppose to overlay and everything worked great. So RelativeLayout, DroidDraw and you are good to go :) Simple, no any kind of jiggery pockery :) and here is a bit of code for ya:
The logo is going to be on top of shazam background image.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="@+id/widget39"
android:layout_width="219px"
android:layout_height="225px"
android:src="@drawable/shazam_bkgd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
<ImageView
android:id="@+id/widget37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/shazam_logo"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
</RelativeLayout>
You have to modify two possible limits:
In conf\server.xml
<Connector port="80" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxPostSize="67589953" />
In webapps\manager\WEB-INF\web.xml
<multipart-config>
<!-- 52MB max -->
<max-file-size>52428800</max-file-size>
<max-request-size>52428800</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
In my case, it was a missing line break that added unneeded parameters due to a bad copy and paste.
I followed a guide at https://pytorch.org/docs/stable/notes/windows.html#include-optional-components which looks like this when you copy it right here without any editing:
REM Make sure you have 7z and curl installed.
REM Download MKL files
curl https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z -k -O 7z x -aoa mkl_2020.0.166.7z -omkl
Output:
C:\Users\Admin>curl "https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z" -k -O 7z x
-aoa mkl_2020.0.166.7z -omkl
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 103M 100 103M 0 0 5063k 0 0:00:21 0:00:21 --:--:-- 5629k
0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0curl: (6) Could not resolve host: 7z
0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0curl: (6) Could not resolve host: x
curl: (6) Could not resolve host: mkl_2020.0.166.7z
There is actually a line break before "7z", with "7z" as the executable (and before, in addition to adding curl to your user PATH
, you need to add 7z to the user PATH
as well, for example with setx PATH "%PATH%;C:\Program Files\7-Zip\"
):
REM Download MKL files
curl https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z -k -O
7z x -aoa mkl_2020.0.166.7z -omkl
You can determine if as certain word is found in a cell by using
If InStr(cell.Value, "Word1") > 0 Then
If Word1 is found in the string the InStr()
function will return the location of the first character of Word1 in the string.
Need to set the foreign key option as on delete cascade... in tables which contains foreign key columns.... It need to set at the time of table creation or add later using ALTER table
It's also useful to note that you can run the underlying MapReduce jobs with either the source or target cluster like so:
hadoop --config /path/to/hadoop/config distcp <src> <dst>
Make sure the hamcrest jar is higher on the import order than your JUnit jar.
JUnit comes with its own org.hamcrest.Matcher
class that is probably being used instead.
You can also download and use the junit-dep-4.10.jar instead which is JUnit without the hamcrest classes.
mockito also has the hamcrest classes in it as well, so you may need to move\reorder it as well
I have try to my code and got success try this
package com.mobeyosoft.latitudelongitude;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* Created by 5943 6417 on 14-09-2016.
*/
public class LocationService extends Service
{
public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 1;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
Context context;
Intent intent;
int counter = 0;
@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
context=this;
}
@Override
public void onStart(Intent intent, int startId) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
}
@Override
public IBinder onBind(Intent intent){
return null;
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public void onDestroy() {
// handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
Log.v("STOP_SERVICE", "DONE");
locationManager.removeUpdates(listener);
}
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
@Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
public class MyLocationListener implements LocationListener{
public void onLocationChanged(final Location loc)
{
Log.i("**********", "Location changed");
if(isBetterLocation(loc, previousBestLocation)) {
loc.getLatitude();
loc.getLongitude();
Toast.makeText(context, "Latitude" + loc.getLatitude() + "\nLongitude"+loc.getLongitude(),Toast.LENGTH_SHORT).show();
intent.putExtra("Latitude", loc.getLatitude());
intent.putExtra("Longitude", loc.getLongitude());
intent.putExtra("Provider", loc.getProvider());
sendBroadcast(intent);
}
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
This is a peculiar question because it's not supposed to be a matter of choice.
When you launch the JVM, you specify a class to run, and it is the main()
of this class where your program starts.
By init()
, I assume you mean the JApplet method. When an applet is launched in the browser, the init()
method of the specified applet is executed as the first order of business.
By run()
, I assume you mean the method of Runnable. This is the method invoked when a new thread is started.
If Eclipse is running your run()
method even though you have no main()
, then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.
You are just missing to make it raw. The issue is with "\". Adding r before the path would do the work :)
import os
os.system(r"D:\xxx1\xxx2XMLnew\otr.bat")
No need for "tricks". Python 3.3 comes with PyLauncher "py.exe", installs it in the path, and registers it as the ".py" extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run:
#!python2
print "hello"
Or
#!python3
print("hello")
From the command line:
py -3 hello.py
Or
py -2 hello.py
py hello.py
by itself will choose the latest Python installed, or consult the PY_PYTHON
environment variable, e.g. set PY_PYTHON=3.6
.
Cygwin can give you this functionality.
The Accept Ranges
header (the bit in writeHead()
) is required for the HTML5 video controls to work.
I think instead of just blindly send the full file, you should first check the Accept Ranges
header in the REQUEST, then read in and send just that bit. fs.createReadStream
support start
, and end
option for that.
So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat
to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream
to send the requested part to the client.
var fs = require("fs"),
http = require("http"),
url = require("url"),
path = require("path");
http.createServer(function (req, res) {
if (req.url != "/movie.mp4") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
} else {
var file = path.resolve(__dirname,"movie.mp4");
fs.stat(file, function(err, stats) {
if (err) {
if (err.code === 'ENOENT') {
// 404 Error if file not found
return res.sendStatus(404);
}
res.end(err);
}
var range = req.headers.range;
if (!range) {
// 416 Wrong range
return res.sendStatus(416);
}
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
var total = stats.size;
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/mp4"
});
var stream = fs.createReadStream(file, { start: start, end: end })
.on("open", function() {
stream.pipe(res);
}).on("error", function(err) {
res.end(err);
});
});
}
}).listen(8888);
Here I include how a friend of mine solved the problem of displaying videos in HTML in Nexus One:
I never was able to make the video play inline. Actually many people on the internet mention explicitly that inline video play in HTML is supported since Honeycomb, and we were fighting with Froyo and Gingerbread... Also for smaller phones I think that playing full screen is very natural - otherwise not so much is visible. So the goal was to make the video open in full screen. However, the proposed solutions in this thread did not work for us - clicking on the element triggered nothing. Furthermore the video controls were shown, but no poster was displayed so the user experience was even weirder. So what he did was the following:
Expose native code to the HTML to be callable via javascript:
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
The code itself, had a function that called native activity to play the video:
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
public void startVideo(String videoAddress){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(videoAddress), "video/3gpp"); // The Mime type can actually be determined from the file
activity.startActivity(intent);
}
}
Then in the HTML itself he kept on failing make the video tag work playing the video. Thus, finally he decided to overwrite the onclick
event of the video, making it do the actual play. This almost worked for him - except for no poster was displayed. Here comes the most weird part - he kept on receiving ERROR/AndroidRuntime(7391): java.lang.RuntimeException: Null or empty value for header "Host"
every time he set the poster
attribute of the tag. Finally he found the issue, which was very weird - it turned out that he had kept the source
subtag in the video
tag, but never used it. And weird enough exactly this was causing the problem. Now see his definition of the video
section:
<video width="320" height="240" controls="controls" poster='poster.gif' onclick="playVideo('file:///sdcard/test.3gp');" >
Your browser does not support the video tag.
</video>
Of course you need to also add the definition of the javascript function in the head of the page:
<script>
function playVideo(video){
window.JSInterface.startVideo(video);
}
</script>
I realize this is not purely HTML solution, but is the best we were able to do for Nexus One type of phone. All credits for this solution go to Dimitar Zlatkov Dimitrov.
For anybody else stumbling over this, the same happened to me while trying to send a SOAP request header to a SOAP service. The issue was a wrong order in the code, I requested the input stream first before sending the XML body. In the code snipped below, the line InputStream in = conn.getInputStream();
came immediately after ByteArrayOutputStream out = new ByteArrayOutputStream();
which is the incorrect order of things.
ByteArrayOutputStream out = new ByteArrayOutputStream();
// send SOAP request as part of HTTP body
byte[] data = request.getHttpBody().getBytes("UTF-8");
conn.getOutputStream().write(data);
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d(TAG, "http response code is " + conn.getResponseCode());
return null;
}
InputStream in = conn.getInputStream();
FileNotFound
in this case was an unfortunate way to encode HTTP response code 400.
dirname(parent.frame(2)$ofile)
doesn't work for me either, but the following (as suggested in https://stackoverflow.com/a/35842176/992088) works for me in ubuntu 14.04
dirname(rstudioapi::getActiveDocumentContext()$path)
Try using a callback like this with the catch block.
document.getElementById("audio").play().catch(function() {
// do something
});
Typically, one follow the conventions used in the language's standard library.
With sdk, you can't write to the root of internal storage. This cause your error.
Edit :
Based on your code, to use internal storage with sdk:
final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");
According to the StyleCop Rules Documentation the ordering is as follows.
Within a class, struct or interface: (SA1201 and SA1203)
Within each of these groups order by access: (SA1202)
Within each of the access groups, order by static, then non-static: (SA1204)
Within each of the static/non-static groups of fields, order by readonly, then non-readonly : (SA1214 and SA1215)
An unrolled list is 130 lines long, so I won't unroll it here. The methods part unrolled is:
The documentation notes that if the prescribed order isn't suitable - say, multiple interfaces are being implemented, and the interface methods and properties should be grouped together - then use a partial class to group the related methods and properties together.
There are only function scopes in JS. Not block scopes! You can see what is hoisting too.
var global_variable = "global_variable";
var hoisting_variable = "global_hoist";
// Global variables printed
console.log("global_scope: - global_variable: " + global_variable);
console.log("global_scope: - hoisting_variable: " + hoisting_variable);
if (true) {
// The variable block will be global, on true condition.
var block = "block";
}
console.log("global_scope: - block: " + block);
function local_function() {
var local_variable = "local_variable";
console.log("local_scope: - local_variable: " + local_variable);
console.log("local_scope: - global_variable: " + global_variable);
console.log("local_scope: - block: " + block);
// The hoisting_variable is undefined at the moment.
console.log("local_scope: - hoisting_variable: " + hoisting_variable);
var hoisting_variable = "local_hoist";
// The hoisting_variable is now set as a local one.
console.log("local_scope: - hoisting_variable: " + hoisting_variable);
}
local_function();
// No variable in a separate function is visible into the global scope.
console.log("global_scope: - local_variable: " + local_variable);
The vtables are created by the compiler. A class object has a pointer to its vtable. When it starts life, that vtable pointer points to the vtable of the base class. At the end of the constructor code, the compiler generates code to re-point the vtable pointer to the actual vtable for the class. This ensures that constructor code that calls virtual functions calls the base class implementations of those functions, not the override in the class.
Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
Should be:
Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')
Private Sub DataGridView1_CellClick(ByVal sender As System.Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellClick
MsgBox(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
End Sub
When using google gson library.
var getRowData =
[{
"dayOfWeek": "Sun",
"date": "11-Mar-2012",
"los": "1",
"specialEvent": "",
"lrv": "0"
},
{
"dayOfWeek": "Mon",
"date": "",
"los": "2",
"specialEvent": "",
"lrv": "0.16"
}];
JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
JsonArray jsonArray = root.getAsJsonArray();
JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject();
String dayOfWeek = jsonObject1.get("dayOfWeek").toString();
// when using jackson library
JsonFactory f = new JsonFactory();
ObjectMapper mapper = new ObjectMapper();
JsonParser jp = f.createJsonParser(getRowData);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT) {
Map<String,Object> userData = mapper.readValue(jp, Map.class);
userData.get("dayOfWeek");
// process
// after binding, stream points to closing END_OBJECT
}
Omit the parenthesis:
ALTER TABLE User
ADD CONSTRAINT userProperties
FOREIGN KEY(properties)
REFERENCES Properties(ID)
You can add virtual columns as
SELECT '1' as temp
But if you tries to put where condition to additionally generated column, it wont work and will show an error message as the column doesn't exist.
We can solve this issue by returning sql result as a table.ie,
SELECT tb.* from (SELECT 1 as temp) as tb WHERE tb.temp = 1
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php
so your javascript can download the XML file. You are trying to do too many things in the same file.
Do git help gitignore
You will get the help page with following line:
A line starting with # serves as a comment.
As a complementary, for those who might meet the same issue as mine, I'm using $.ajax
to post form data to server and I also got the 400
error at first.
Assume I have a javascript variable,
var formData = {
"name":"Gearon",
"hobby":"Be different"
};
Do not use variable formData
directly as the value of key data
like below:
$.ajax({
type: "post",
dataType: "json",
url: "http://localhost/user/add",
contentType: "application/json",
data: formData,
success: function(data, textStatus){
alert("Data: " + data + "\nStatus: " + status);
}
});
Instead, use JSON.stringify to encapsulate the formData
as below:
$.ajax({
type: "post",
dataType: "json",
url: "http://localhost/user/add",
contentType: "application/json",
data: JSON.stringify(formData),
success: function(data, textStatus){
alert("Data: " + data + "\nStatus: " + status);
}
});
Anyway, as others have illustrated, the error is because the server could not recognize the request cause malformed syntax, I'm just raising a instance at practice. Hope it would be helpful to someone.
Re: SELECT * INTO OUTFILE
Check if MySQL has permissions to write a file to the OUTFILE directory on the server.
lambda lst: reduce(lambda a,b:(b,b==a[0] and a[1]), lst, (lst[0], True))[1]
The next one will short short circuit:
all(itertools.imap(lambda i:yourlist[i]==yourlist[i+1], xrange(len(yourlist)-1)))
Here you can see the difference between the way that deceze offered comparing to the simple array_values
approach:
The Array:
$array['a'][0] = array('x' => 1, 'y' => 2, 'z' => 3);
$array['a'][5] = array('x' => 4, 'y' => 5, 'z' => 6);
$array['b'][1] = array('x' => 7, 'y' => 8, 'z' => 9);
$array['b'][7] = array('x' => 10, 'y' => 11, 'z' => 12);
In deceze
way, here is your output:
$array = array_map('array_values', $array);
print_r($array);
/* Output */
Array
(
[a] => Array
(
[0] => Array
(
[x] => 1
[y] => 2
[z] => 3
)
[1] => Array
(
[x] => 4
[y] => 5
[z] => 6
)
)
[b] => Array
(
[0] => Array
(
[x] => 7
[y] => 8
[z] => 9
)
[1] => Array
(
[x] => 10
[y] => 11
[z] => 12
)
)
)
And here is your output if you only use array_values
function:
$array = array_values($array);
print_r($array);
/* Output */
Array
(
[0] => Array
(
[0] => Array
(
[x] => 1
[y] => 2
[z] => 3
)
[5] => Array
(
[x] => 4
[y] => 5
[z] => 6
)
)
[1] => Array
(
[1] => Array
(
[x] => 7
[y] => 8
[z] => 9
)
[7] => Array
(
[x] => 10
[y] => 11
[z] => 12
)
)
)
Add using System.Linq;
at the top of your file. Then you can do:
if ((new [] {"foo", "bar", "baaz"}).Contains("bar"))
{
}