The includes
(formerly called contains
and include
) method compares objects by reference (or more precisely, with ===
). Because the two object literals of {"b": 2}
in your example represent different instances, they are not equal. Notice:
({"b": 2} === {"b": 2})
> false
However, this will work because there is only one instance of {"b": 2}
:
var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true
On the other hand, the where
(deprecated in v4) and find
methods compare objects by their properties, so they don't require reference equality. As an alternative to includes
, you might want to try some
(also aliased as any
):
_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true
I thought I will post my answer as I recently got into a similar issue (as of September 2019). The App is free for all users in all countries.
For me, after I received a confirmation email from Apple saying that my app is ready for sale (the email did not mention any 24 hours waiting period), I could not find my App in the App Store.
The link to view the App in the App Store in the iTunes Connect (under the App Information section at the bottom page) was broken.
After reading your comments in this thread, I went to the Pricing and Availability section of the App and edited the pricing plan again to be 0 GBP and start date Today and finish date No Finish Date.
Then, I unchecked the countries the App is available on and checked them all again and hit Save.
The App became immediately available in the App store. The link in the App information section was directing me to the App Store and no longer broken.
I hope this will help anyone who is having similar issues lately (getting a confirmation email that the App is ready for sale but cannot find it in the App Store).
This isn't really a fixing solution but it may help others. Unlike Nick had said for me it was due to code in my program. I have the mega ADK model. The issue was tied to a switch statement for processing and parsing the returned byte[] from the usb connection to the Android. Its very strange because it would compile perfectly every time but would fail as the OP had stated. I commented it out and it worked fine.
I used the following:
delta = timedelta()
totalMinute, second = divmod(delta.seconds, 60)
hour, minute = divmod(totalMinute, 60)
print(f"{hour}h{minute:02}m{second:02}s")
contents_re = re.match(r'[^\(]*\((?P<contents>[^\(]+)\)', data)
if contents_re:
print(contents_re.groupdict()['contents'])
The simplest way I think is 'Ctrl+P' > save as 'pdf'. That's it.
In my case, just one cell was having this problem. The cell included UITextView outlet in readonly mode. Though it was readonly before tap. Upon tapping, keyboard rose. It turned out that it still needed to disable the interaction.
cell.content.scrollEnabled = NO;
cell.content.editable = NO;
cell.content.userInteractionEnabled = NO;
cell.content.delegate = nil;
[cell.content resignFirstResponder];
I'm not quite sure what you're asking, but maybe this can help:
window.onload = function(){
// Code. . .
}
Or:
window.onload = main;
function main(){
// Code. . .
}
Personally, I prefer changing the method signature to:
public ResponseEntity<?>
This gives the advantage of possibly returning an error message as single item for services which, when ok, return a list of items.
When returning I don't use any type (which is unused in this case anyway):
return new ResponseEntity<>(entities, HttpStatus.OK);
The cross-platform way to do this is to print('\a')
. This will send the ASCII Bell character to stdout, and will hopefully generate a beep (a for 'alert'). Note that many modern terminal emulators provide the option to ignore bell characters.
Since you're on Windows, you'll be happy to hear that Windows has its own (brace yourself) Beep API, which allows you to send beeps of arbitrary length and pitch. Note that this is a Windows-only solution, so you should probably prefer print('\a')
unless you really care about Hertz and milliseconds.
The Beep API is accessed through the winsound module: http://docs.python.org/library/winsound.html
There are a few things to change in your edited version:
You've taken the suggestion of using document.myform['whichThing']
a bit too literally. Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].
There's no such thing as an action
attribute for the <input>
tag. Use onclick
instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Obtaining and cancelling an Event object in a browser is a very involved process. It varies a lot by browser type and version. IE and Firefox handle these things very differently, so a simple event.preventDefault()
won't work... in fact, the event variable probably won't even be defined because this is an onclick handler from a tag. This is why Stephen above is trying so hard to suggest a framework. I realize you want to know the mechanics, and I recommend google for that. In this case, as a simple workaround, use return false
in the onclick tag as in number 2 above (or return false from the function as stephen suggested).
Because of #3, get rid of everything not the alert statement in your handler.
The code should now look like:
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
}
</script>
</head>
<body>
<form name="aye">
<input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
#include <stdint.h>
//! Byte swap unsigned short
uint16_t swap_uint16( uint16_t val )
{
return (val << 8) | (val >> 8 );
}
//! Byte swap short
int16_t swap_int16( int16_t val )
{
return (val << 8) | ((val >> 8) & 0xFF);
}
//! Byte swap unsigned int
uint32_t swap_uint32( uint32_t val )
{
val = ((val << 8) & 0xFF00FF00 ) | ((val >> 8) & 0xFF00FF );
return (val << 16) | (val >> 16);
}
//! Byte swap int
int32_t swap_int32( int32_t val )
{
val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF );
return (val << 16) | ((val >> 16) & 0xFFFF);
}
Update : Added 64bit byte swapping
int64_t swap_int64( int64_t val )
{
val = ((val << 8) & 0xFF00FF00FF00FF00ULL ) | ((val >> 8) & 0x00FF00FF00FF00FFULL );
val = ((val << 16) & 0xFFFF0000FFFF0000ULL ) | ((val >> 16) & 0x0000FFFF0000FFFFULL );
return (val << 32) | ((val >> 32) & 0xFFFFFFFFULL);
}
uint64_t swap_uint64( uint64_t val )
{
val = ((val << 8) & 0xFF00FF00FF00FF00ULL ) | ((val >> 8) & 0x00FF00FF00FF00FFULL );
val = ((val << 16) & 0xFFFF0000FFFF0000ULL ) | ((val >> 16) & 0x0000FFFF0000FFFFULL );
return (val << 32) | (val >> 32);
}
The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.
Refer below URL
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
make sure that you are using the same namespace as your pages
filter: blur(0)
transition: filter .3s ease-out
transition-timing-function: steps(3, end) // add this string with steps equal duration
I was helped by setting the value of transition duration .3s
equal transition timing steps .3s
Converting a date String of the format "2011-06-23T15:11:32" to our time zone.
private String getDate(String ourDate)
{
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(ourDate);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM-dd-yyyy HH:mm"); //this format changeable
dateFormatter.setTimeZone(TimeZone.getDefault());
ourDate = dateFormatter.format(value);
//Log.d("ourDate", ourDate);
}
catch (Exception e)
{
ourDate = "00-00-0000 00:00";
}
return ourDate;
}
You can do by using a custom middleware, even though knowing that the best option is using the tested approach of the package django-cors-headers
. With that said, here is the solution:
create the following structure and files:
-- myapp/middleware/__init__.py
from corsMiddleware import corsMiddleware
-- myapp/middleware/corsMiddleware.py
class corsMiddleware(object):
def process_response(self, req, resp):
resp["Access-Control-Allow-Origin"] = "*"
return resp
add to settings.py
the marked line:
MIDDLEWARE_CLASSES = (
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
# Now we add here our custom middleware
'app_name.middleware.corsMiddleware' <---- this line
)
Just for the sake of completeness, here is another very simple solution, which will most likely take a very long time to run, but uses very little memory.
Let all possible integers be the range from int_min
to int_max
, and
bool isNotInFile(integer)
a function which returns true if the file does not contain a certain integer and false else (by comparing that certain integer with each integer in the file)
for (integer i = int_min; i <= int_max; ++i)
{
if (isNotInFile(i)) {
return i;
}
}
seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path
See:
The Difference Between a Program and a Script
A Script is also a program but without an opaque layer hiding the (source code) whereas a program is one having clothes, you can't see it's source code unless it is decompilable.
Scripts need other programs to execute them while programs don't need one.
I used modified (added signed_request param to the link) Whiteagle's trick and it worked ok for safari, but IE is constantly refreshing the page in that case. So my solution for safari and internet explorer is:
$fbapplink = 'https://apps.facebook.com/[appnamespace]/';
$isms = stripos($_SERVER['HTTP_USER_AGENT'], 'msie') !== false;
// safari fix
if(! $isms && !isset($_SESSION['signed_request'])) {
if (isset($_GET["start_session"])) {
$_SESSION['signed_request'] = $_GET['signed_request'];
die(header("Location:" . $fbapplink ));
}
if (!isset($_GET["sid"])) {
die(header("Location:?sid=" . session_id() . '&signed_request='.$_REQUEST['signed_request']));
}
$sid = session_id();
if (empty($sid) || $_GET["sid"] != $sid) {
?>
<script>
top.window.location="?start_session=true";
</script>
<?php
exit;
}
}
// IE fix
header('P3P: CP="CAO PSA OUR"');
header('P3P: CP="HONK"');
.. later in the code
$sr = $_REQUEST['signed_request'];
if($sr) {
$_SESSION['signed_request'] = $sr;
} else {
$sr = $_SESSION['signed_request'];
}
it is dxd, not ddx
if you want to delete 5 lines, cursor to the beginning of the first line to delete and d5d
I also use OleDbDataReader.IsDBNull()
if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
else { retrievedValue = myReader.GetString(colNum); }
I will post my answer here since it's the first result in google's search
1) react-native unlink <Module Name>
2) npm unlink <Module Name>
3) npm uninstall --save <Module name
While Dictionary is implemented as a hash table, SortedDictionary is implemented as a Red-Black Tree.
If you don't take advantage of the order in your algorithm and only need to sort the data before output, using SortedDictionary would have negative impact on performance.
You can "sort" the dictionary like this:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
// algorithm
return new SortedDictionary<string, int>(dictionary);
You would have to tune it according to your environment.
Sometimes it's more useful to increase the size of the backlog (acceptCount) instead of the maximum number of threads.
Say, instead of
<Connector ... maxThreads="500" acceptCount="50"
you use
<Connector ... maxThreads="300" acceptCount="150"
you can get much better performance in some cases, cause there would be less threads disputing the resources and the backlog queue would be consumed faster.
In any case, though, you have to do some benchmarks to really know what is best.
You can do this :
mysql -u USERNAME --password=PASSWORD --database=DATABASE --execute='SELECT `FIELD`, `FIELD` FROM `TABLE` LIMIT 0, 10000 ' -X > file.xml
I use below sql to exclude the null string and empty string lines.
select * from table where length(nvl(column1,0))>0
Because, the length of empty string is 0.
select length('');
+-----------+--+
| length() |
+-----------+--+
| 0 |
+-----------+--+
Control characters:
(Hex codes assume an ASCII-compatible character encoding.)
\a
= \x07
= alert (bell)\b
= \x08
= backspace\t
= \x09
= horizonal tab\n
= \x0A
= newline (or line feed)\v
= \x0B
= vertical tab\f
= \x0C
= form feed\r
= \x0D
= carriage return\e
= \x1B
= escape (non-standard GCC extension)Punctuation characters:
\"
= quotation mark (backslash not required for '"'
)\'
= apostrophe (backslash not required for "'"
)\?
= question mark (used to avoid trigraphs)\\
= backslashNumeric character references:
\
+ up to 3 octal digits\x
+ any number of hex digits\u
+ 4 hex digits (Unicode BMP, new in C++11)\U
+ 8 hex digits (Unicode astral planes, new in C++11)\0
= \00
= \000
= octal ecape for null character
If you do want an actual digit character after a \0
, then yes, I recommend string concatenation. Note that the whitespace between the parts of the literal is optional, so you can write "\0""0"
.
SHOW CREATE TABLE yourTable;
or
SHOW COLUMNS FROM yourTable;
Your problem is those pernicious double quotes.
SQL> CREATE TABLE "APC"."PS_TBL_DEPARTMENT_DETAILS"
2 (
3 "Company Code" VARCHAR2(255),
4 "Company Name" VARCHAR2(255),
5 "Sector_Code" VARCHAR2(255),
6 "Sector_Name" VARCHAR2(255),
7 "Business_Unit_Code" VARCHAR2(255),
8 "Business_Unit_Name" VARCHAR2(255),
9 "Department_Code" VARCHAR2(255),
10 "Department_Name" VARCHAR2(255),
11 "HR_ORG_ID" VARCHAR2(255),
12 "HR_ORG_Name" VARCHAR2(255),
13 "Cost_Center_Number" VARCHAR2(255),
14 " " VARCHAR2(255)
15 )
16 /
Table created.
SQL>
Oracle SQL allows us to ignore the case of database object names provided we either create them with names all in upper case, or without using double quotes. If we use mixed case or lower case in the script and wrapped the identifiers in double quotes we are condemned to using double quotes and the precise case whenever we refer to the object or its attributes:
SQL> select count(*) from PS_TBL_DEPARTMENT_DETAILS
2 where Department_Code = 'BAH'
3 /
where Department_Code = 'BAH'
*
ERROR at line 2:
ORA-00904: "DEPARTMENT_CODE": invalid identifier
SQL> select count(*) from PS_TBL_DEPARTMENT_DETAILS
2 where "Department_Code" = 'BAH'
3 /
COUNT(*)
----------
0
SQL>
tl;dr
don't use double quotes in DDL scripts
(I know most third party code generators do, but they are disciplined enough to put all their object names in UPPER CASE.)
The reverse is also true. If we create the table without using double-quotes …
create table PS_TBL_DEPARTMENT_DETAILS
( company_code VARCHAR2(255),
company_name VARCHAR2(255),
Cost_Center_Number VARCHAR2(255))
;
… we can reference it and its columns in whatever case takes our fancy:
select * from ps_tbl_department_details
… or
select * from PS_TBL_DEPARTMENT_DETAILS;
… or
select * from PS_Tbl_Department_Details
where COMAPNY_CODE = 'ORCL'
and cost_center_number = '0980'
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
Now it makes sense to do 2 ways in the view model. if you want to save the first as a saved instance: You can add state parameter in view model like this https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate#java
or you can save variables or object in view model, in this case the view model will hold the life cycle until the activity is destroyed.
public class HelloAndroidViewModel extends ViewModel {
public Booelan firstInit = false;
public HelloAndroidViewModel() {
firstInit = false;
}
...
}
public class HelloAndroid extends Activity {
private TextView mTextView = null;
HelloAndroidViewModel viewModel = ViewModelProviders.of(this).get(HelloAndroidViewModel.class);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = new TextView(this);
//Because even if the state is deleted, the data in the viewmodel will be kept because the activity does not destroy
if(!viewModel.firstInit){
viewModel.firstInit = true
mTextView.setText("Welcome to HelloAndroid!");
}else{
mTextView.setText("Welcome back.");
}
setContentView(mTextView);
}
}
In the menu.xml
you should add all the menu items. Then you can hide items that you don't want to see in the initial loading.
menu.xml
<item
android:id="@+id/action_newItem"
android:icon="@drawable/action_newItem"
android:showAsAction="never"
android:visible="false"
android:title="@string/action_newItem"/>
Add setHasOptionsMenu(true)
in the onCreate() method to invoke the menu items in your Fragment class.
FragmentClass.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
You don't need to override onCreateOptionsMenu
in your Fragment class again. Menu items can be changed (Add/remove) by overriding onPrepareOptionsMenu
method available in Fragment.
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_newItem).setVisible(true);
super.onPrepareOptionsMenu(menu);
}
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.
A good start for clarifying the best practice is to follow this tutorial:
https://codeigniter.com/user_guide/tutorial/index.html
It's simple, but it really lays out an excellent how-to.
I hope this helps!
Yes, with JPA 2.1 it's easy. You have very useful Annotations. They simplify your life.
First declare your native query, then your result set mapping (which defines the mapping of the data returned by the database to your POJOs). Write your POJO class to refer to (not included here for brevity). Last but not least: create a method in a DAO (for example) to call the query. This worked for me in a dropwizard (1.0.0) app.
First declare a native query in an entity class:
@NamedNativeQuery (
name = "domain.io.MyClass.myQuery",
query = "Select a.colA, a.colB from Table a",
resultSetMapping = "mappinMyNativeQuery") // must be the same name as in the SqlResultSetMapping declaration
Underneath you can add the resultset mapping declaration:
@SqlResultSetMapping(
name = "mapppinNativeQuery", // same as resultSetMapping above in NativeQuery
classes = {
@ConstructorResult(
targetClass = domain.io.MyMapping.class,
columns = {
@ColumnResult( name = "colA", type = Long.class),
@ColumnResult( name = "colB", type = String.class)
}
)
}
)
Later in a DAO you can refer to the query as
public List<domain.io.MyMapping> findAll() {
return (namedQuery("domain.io.MyClass.myQuery").list());
}
That's it.
I know this question has already been marked as answered, but let me plug my own library here. It's called inspect.lua, and you can find it here:
https://github.com/kikito/inspect.lua
It's just a single file that you can require from any other file. It returns a function that transforms any Lua value into a human-readable string:
local inspect = require('inspect')
print(inspect({1,2,3})) -- {1, 2, 3}
print(inspect({a=1,b=2})
-- {
-- a = 1
-- b = 2
-- }
It indents subtables properly, and handles "recursive tables" (tables that contain references to themselves) correctly, so it doesn't get into infinite loops. It sorts values in a sensible way. It also prints metatable information.
Regards!
In this answer I will describe the three methods of defining DOM event handlers.
element.addEventListener()
Code example:
const element = document.querySelector('a');_x000D_
element.addEventListener('click', event => event.preventDefault(), true);
_x000D_
<a href="//google.com">Try clicking this link.</a>
_x000D_
element.addEventListener()
has multiple advantages:
element.removeEventListener()
.useCapture
parameter, which indicates whether you'd like to handle event in its capturing or bubbling phase. See: Unable to understand useCapture attribute in addEventListener..onevent
properties of DOM elements, lots of inexperienced JavaScript programmers thinks that the event name is for example onclick
or onload
. on
is not a part of event name. Correct event names are click
and load
, and that's how event names are passed to .addEventListener()
.element.onevent = function() {}
(e.g. onclick
, onload
)Code example:
const element = document.querySelector('a');_x000D_
element.onclick = event => event.preventDefault();
_x000D_
<a href="//google.com">Try clicking this link.</a>
_x000D_
This was a way to register event handlers in DOM 0. It's now discouraged, because it:
onevent
property back to its initial state (i.e. null
).window.onload
, for example: window.onload = "test";
, it won't throw any errors. Your code wouldn't work and it would be really hard to find out why. .addEventListener()
however, would throw error (at least in Firefox): TypeError: Argument 2 of EventTarget.addEventListener is not an object.onevent
HTML attribute)Code example:
<a href="//google.com" onclick="event.preventDefault();">Try clicking this link.</a>
_x000D_
Similarly to element.onevent
, it's now discouraged. Besides the issues that element.onevent
has, it:
Content-Security-Policy
HTTP header to block inline scripts and allow external scripts only from trusted domains. See How does Content Security Policy work?THis issue has been fixed with new mysql connectors, please use http://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.38
I used to get this error after updating the connector jar, issue resolved.
<EditText
android:id="@+id/et_password_tlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:textColorHint="#9e9e9e"
android:backgroundTint="#000"
android:singleLine="true"
android:drawableTint="#FF4081"
android:paddingTop="25dp"
android:textColor="#000"
android:paddingBottom="5dp"
android:inputType="textPassword"/>
<View
android:id="@+id/UnderLine"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="@+id/et_password_tlay"
android:layout_centerHorizontal="true"
android:background="#03f94e" />
**it one of doing with view **
If you login into the source control with the admin account, you will be able to force undo checkout, or check in with any file you provide.
There is a workaround to solve this problem by using a derived table.
DELETE t1 FROM test t1 JOIN (SELECT t.id FROM test LIMIT 1) t2 ON t1.id = t2.id
Because the LIMIT is inside the derived table the join will match only 1 row and thus the query will delete only this row.
To save and load an arraylist of public static ArrayList data = new ArrayList ();
I used (to write)...
static void saveDatabase() {
try {
FileOutputStream fos = new FileOutputStream("mydb.fil");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
databaseIsSaved = true;
}
catch (IOException e) {
e.printStackTrace();
}
} // End of saveDatabase
And used (to read) ...
static void loadDatabase() {
try {
FileInputStream fis = new FileInputStream("mydb.fil");
ObjectInputStream ois = new ObjectInputStream(fis);
data = (ArrayList<User>)ois.readObject();
ois.close();
}
catch (IOException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
} // End of loadDatabase
You can always use Request.QueryString
collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.
This solution is similar to walid2mi (thank you for inspiration), but allows the standard console input by the Read-Host cmdlet.
pros:
cons:
Commented and runable example of batch-ps-script.cmd:
<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd %~dp0
: Invoke this file as powershell expression
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script
# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"
# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
Write-Host "Exit script..."
break
}
# example: call standard powershell command
Get-Item .
Snippet for .cmd file:
<# : batch script
@echo off
setlocal
cd %~dp0
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
endlocal
goto:eof
#>
# here write your powershell commands...
Finds the biggest and the smallest number in the array:
int[] arr = new int[] {35,28,20,89,63,45,12};
int big = 0;
int little = 0;
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
if (arr[i] > arr[0])
{
big = arr[i];
}
else
{
little = arr[i];
}
}
Console.WriteLine("most big number inside of array is " + big);
Console.WriteLine("most little number inside of array is " + little);
The best explanation of how core.autocrlf
works is found on the gitattributes man page, in the text
attribute section.
This is how core.autocrlf
appears to work currently (or at least since v1.7.2 from what I am aware):
core.autocrlf = true
LF
characters are normalized to CRLF
in your working tree; files that contain CRLF
in the repository will not be touchedLF
characters in the repository, are normalized from CRLF
to LF
when committed back to the repository. Files that contain CRLF
in the repository will be committed untouched.core.autocrlf = input
CRLF
characters are normalized to LF
when committed back to the repository.core.autocrlf = false
core.eol
dictates EOL characters in the text files of your working tree.core.eol = native
by default, which means Windows EOLs are CRLF
and *nix EOLs are LF
in working trees.gitattributes
settings determines EOL character normalization for commits to the repository (default is normalization to LF
characters).I've only just recently researched this issue and I also find the situation to be very convoluted. The core.eol
setting definitely helped clarify how EOL characters are handled by git.
There's a free php script made by Celeron Dude that can do this called Celeron Dude Indexer 2. It doesn't require .htaccess
The source code is easy to understand and provides a good starting point.
Here's a download link: https://gitlab.com/desbest/celeron-dude-indexer/
Use Val(txtPrice.text)
I would also allow only number and the dot char by inserting some validation code in the key press event of the price text box.
The files selected are stored in an array: [input].files
For example, you can access the items
// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
For jQuery-comfortable people, it's similarly easy
// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:
Session session = entityManager.unwrap(Session.class);
That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.
I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.
I would like to add required attribute in case user disabled javascript:
<input type="text" id="textbox" required/>
It works on all modern browsers.
Both T1
and T2
can refer to a class containing this variable.
You can then make this variable volatile, and this means that
Changes to that variable are immediately visible in both threads.
See this article for more info.
Volatile variables share the visibility features of synchronized but none of the atomicity features. This means that threads will automatically see the most up-to-date value for volatile variables. They can be used to provide thread safety, but only in a very restricted set of cases: those that do not impose constraints between multiple variables or between a variable's current value and its future values.
And note the pros/cons of using volatile
vs more complex means of sharing state.
I'm doing exactly what you're looking for in my rules engine, which uses CS-Script for dynamically compiling, loading, and running C#. It should be easily translatable into what you're looking for, and I'll give an example. First, the code (stripped-down):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using CSScriptLibrary;
namespace RulesEngine
{
/// <summary>
/// Make sure <typeparamref name="T"/> is an interface, not just any type of class.
///
/// Should be enforced by the compiler, but just in case it's not, here's your warning.
/// </summary>
/// <typeparam name="T"></typeparam>
public class RulesEngine<T> where T : class
{
public RulesEngine(string rulesScriptFileName, string classToInstantiate)
: this()
{
if (rulesScriptFileName == null) throw new ArgumentNullException("rulesScriptFileName");
if (classToInstantiate == null) throw new ArgumentNullException("classToInstantiate");
if (!File.Exists(rulesScriptFileName))
{
throw new FileNotFoundException("Unable to find rules script", rulesScriptFileName);
}
RulesScriptFileName = rulesScriptFileName;
ClassToInstantiate = classToInstantiate;
LoadRules();
}
public T @Interface;
public string RulesScriptFileName { get; private set; }
public string ClassToInstantiate { get; private set; }
public DateTime RulesLastModified { get; private set; }
private RulesEngine()
{
@Interface = null;
}
private void LoadRules()
{
if (!File.Exists(RulesScriptFileName))
{
throw new FileNotFoundException("Unable to find rules script", RulesScriptFileName);
}
FileInfo file = new FileInfo(RulesScriptFileName);
DateTime lastModified = file.LastWriteTime;
if (lastModified == RulesLastModified)
{
// No need to load the same rules twice.
return;
}
string rulesScript = File.ReadAllText(RulesScriptFileName);
Assembly compiledAssembly = CSScript.LoadCode(rulesScript, null, true);
@Interface = compiledAssembly.CreateInstance(ClassToInstantiate).AlignToInterface<T>();
RulesLastModified = lastModified;
}
}
}
This will take an interface of type T, compile a .cs file into an assembly, instantiate a class of a given type, and align that instantiated class to the T interface. Basically, you just have to make sure the instantiated class implements that interface. I use properties to setup and access everything, like so:
private RulesEngine<IRulesEngine> rulesEngine;
public RulesEngine<IRulesEngine> RulesEngine
{
get
{
if (null == rulesEngine)
{
string rulesPath = Path.Combine(Application.StartupPath, "Rules.cs");
rulesEngine = new RulesEngine<IRulesEngine>(rulesPath, typeof(Rules).FullName);
}
return rulesEngine;
}
}
public IRulesEngine RulesEngineInterface
{
get { return RulesEngine.Interface; }
}
For your example, you want to call Run(), so I'd make an interface that defines the Run() method, like this:
public interface ITestRunner
{
void Run();
}
Then make a class that implements it, like this:
public class TestRunner : ITestRunner
{
public void Run()
{
// implementation goes here
}
}
Change the name of RulesEngine to something like TestHarness, and set your properties:
private TestHarness<ITestRunner> testHarness;
public TestHarness<ITestRunner> TestHarness
{
get
{
if (null == testHarness)
{
string sourcePath = Path.Combine(Application.StartupPath, "TestRunner.cs");
testHarness = new TestHarness<ITestRunner>(sourcePath , typeof(TestRunner).FullName);
}
return testHarness;
}
}
public ITestRunner TestHarnessInterface
{
get { return TestHarness.Interface; }
}
Then, anywhere you want to call it, you can just run:
ITestRunner testRunner = TestHarnessInterface;
if (null != testRunner)
{
testRunner.Run();
}
It would probably work great for a plugin system, but my code as-is is limited to loading and running one file, since all of our rules are in one C# source file. I would think it'd be pretty easy to modify it to just pass in the type/source file for each one you wanted to run, though. You'd just have to move the code from the getter into a method that took those two parameters.
Also, use your IRunnable in place of ITestRunner.
full path for binary file. For example: /home/vitaliy2034/binary_file_name. Or use directive "./+binary_file_name". './' in unix system it return full path to directory, in which you open terminal(shell). I hope it helps. Sorry, for my english language)
Can't be disabled. Quoting: "Sorry, we know it is annoying, but you the malware writers..."
Your only options are: adapt your automated tests to this new behavior, or upload the offending script to Chrome Web Store (which can be done in an "unlisted" fashion).
You need to look at the Backgroundworker example:
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Especially how it interacts with the UI layer. Based on your posting, this seems to answer your issues.
Your Make file will have one or two dependency rules depending on whether you compile and link with a single command, or with one command for the compile and one for the link.
Dependency are a tree of rules that look like this (note that the indent must be a TAB):
main_target : source1 source2 etc
command to build main_target from sources
source1 : dependents for source1
command to build source1
There must be a blank line after the commands for a target, and there must not be a blank line before the commands. The first target in the makefile is the overall goal, and other targets are built only if the first target depends on them.
So your makefile will look something like this.
a3a.exe : a3driver.obj
link /out:a3a.exe a3driver.obj
a3driver.obj : a3driver.cpp
cc a3driver.cpp
You can use the asXML
method as:
<?php
// string to SimpleXMLElement
$xml = new SimpleXMLElement($string);
// make any changes.
....
// convert the SimpleXMLElement back to string.
$newString = $xml->asXML();
?>
If you wanna find just the word like 'are' in "How are you?" and not like 'are' in 'hare'
$word=" are ";
$str="How are you?";
if(strpos($word,$str) !== false){
echo 1;
}
Updated after Alfe pointed out you don't need to check for float separately as complex handles both:
def is_number(s):
try:
complex(s) # for int, long, float and complex
except ValueError:
return False
return True
Previously said: Is some rare cases you might also need to check for complex numbers (e.g. 1+2i), which can not be represented by a float:
def is_number(s):
try:
float(s) # for int, long and float
except ValueError:
try:
complex(s) # for complex
except ValueError:
return False
return True
Another option to transform the static method into a static Func or Action. For instance.
Original code:
class Math
{
public static int Add(int x, int y)
{
return x + y;
}
You want to "mock" the Add method, but you can't. Change the above code to this:
public static Func<int, int, int> Add = (x, y) =>
{
return x + y;
};
Existing client code doesn't have to change (maybe recompile), but source stays the same.
Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:
[TestMethod]
public static void MyTest()
{
Math.Add = (x, y) =>
{
return 11;
};
Put whatever logic you want in the method, or just return some hard-coded value, depending on what you're trying to do.
This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.
[edit] I suggest that you add the following Cleanup code to your Unit Test class:
[TestCleanup]
public void Cleanup()
{
typeof(Math).TypeInitializer.Invoke(null, null);
}
Add a separate line for each static class. What this does is, after the unit test is done running, it resets all the static fields back to their original value. That way other unit tests in the same project will start out with the correct defaults as opposed your mocked version.
What I would do is comment out the Dockerfile below and including the offending line. Then you can run the container and run the docker commands by hand, and look at the logs in the usual way. E.g. if the Dockerfile is
RUN foo
RUN bar
RUN baz
and it's dying at bar I would do
RUN foo
# RUN bar
# RUN baz
Then
$ docker build -t foo .
$ docker run -it foo bash
container# bar
...grep logs...
Check whether the jars are imported properly. I imported them using build path. But it didn't recognise the jar in WAR/lib folder. Later, I copied the same jar to war/lib folder. It works fine now. You can refresh / clean your project.
I am using React Bootstrap, which is based on Bootstrap 4. The approach is to use Sass, simliar to Nelson Rothermel's answer above.
The idea is to override Bootstraps Sass variable for font family in your custom Sass file. If you are using Google Fonts, then make sure you import it at the top of your custom Sass file.
For example, my custom Sass file is called custom.sass
with the following content:
@import url('https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap');
$font-family-sans-serif: "Dancing Script", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji" !default;
I simply added the font I want to the front of the default values, which can be found in ..\node_modules\boostrap\dist\scss\_variables.scss
.
How the custom.scss
file is used is shown here, which is obtained from here, which is obtained from here...
Because the React app is created by the Create-React-App utility, there's no need to go through all the crufts like Gulp; I just saved the files and React will compile the Sass for me automagically behind the scene.
if (mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')")or die(mysql_error())) {
echo 'Success';
} else {
echo 'Fail';
}
Although since you have or die(mysql_error())
it will show the mysql_error() on the screen when it fails. You should probably remove that if it isnt the desired result
or:
SELECT coalesce(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1
You can use the below sample, also you dont need the else clause to print nothing!
<?php if ( ($cart->count_product) > 0) { ?>
<div class="my_class">
<?php print $cart->count_product; ?>
</div>
<?php } ?>
In this DDJ article, Dan Saks explains one small area where bugs can creep through if you do not typedef your structs (and classes!):
If you want, you can imagine that C++ generates a typedef for every tag name, such as
typedef class string string;
Unfortunately, this is not entirely accurate. I wish it were that simple, but it's not. C++ can't generate such typedefs for structs, unions, or enums without introducing incompatibilities with C.
For example, suppose a C program declares both a function and a struct named status:
int status(); struct status;
Again, this may be bad practice, but it is C. In this program, status (by itself) refers to the function; struct status refers to the type.
If C++ did automatically generate typedefs for tags, then when you compiled this program as C++, the compiler would generate:
typedef struct status status;
Unfortunately, this type name would conflict with the function name, and the program would not compile. That's why C++ can't simply generate a typedef for each tag.
In C++, tags act just like typedef names, except that a program can declare an object, function, or enumerator with the same name and the same scope as a tag. In that case, the object, function, or enumerator name hides the tag name. The program can refer to the tag name only by using the keyword class, struct, union, or enum (as appropriate) in front of the tag name. A type name consisting of one of these keywords followed by a tag is an elaborated-type-specifier. For instance, struct status and enum month are elaborated-type-specifiers.
Thus, a C program that contains both:
int status(); struct status;
behaves the same when compiled as C++. The name status alone refers to the function. The program can refer to the type only by using the elaborated-type-specifier struct status.
So how does this allow bugs to creep into programs? Consider the program in Listing 1. This program defines a class foo with a default constructor, and a conversion operator that converts a foo object to char const *. The expression
p = foo();
in main should construct a foo object and apply the conversion operator. The subsequent output statement
cout << p << '\n';
should display class foo, but it doesn't. It displays function foo.
This surprising result occurs because the program includes header lib.h shown in Listing 2. This header defines a function also named foo. The function name foo hides the class name foo, so the reference to foo in main refers to the function, not the class. main can refer to the class only by using an elaborated-type-specifier, as in
p = class foo();
The way to avoid such confusion throughout the program is to add the following typedef for the class name foo:
typedef class foo foo;
immediately before or after the class definition. This typedef causes a conflict between the type name foo and the function name foo (from the library) that will trigger a compile-time error.
I know of no one who actually writes these typedefs as a matter of course. It requires a lot of discipline. Since the incidence of errors such as the one in Listing 1 is probably pretty small, you many never run afoul of this problem. But if an error in your software might cause bodily injury, then you should write the typedefs no matter how unlikely the error.
I can't imagine why anyone would ever want to hide a class name with a function or object name in the same scope as the class. The hiding rules in C were a mistake, and they should not have been extended to classes in C++. Indeed, you can correct the mistake, but it requires extra programming discipline and effort that should not be necessary.
You have to change the extends Activity to extends AppCompactActivity then try set and getSupportActionBar()
The answer is weaved amongst the various posts here, I'll so my best, but it looks like a really simple and obvious reason.
1) is that there usually is a "user" variable in the udev rule some thing like USER="your_user" probably right after the GROUP="plugdev"
2) You need to use the correct SYSFS{idVendor}==”####" and SYSFS{idProduct}=="####" values for your device/s. If you have devices from more than one manufacture, say like one from Samsung and one from HTC, then you need to have an entry(rule) for each vendor, not an entry for each device but for each different vendor you will use, so you need an entry for HTC and Samsung. It looks like you have your entry for Samsung now you need another. Remember the USER="your_user". Use 'lsusb' like Robert Seimer suggests to find the idVendor and idProduct, they are usually some numbers and letters in this format X#X#:#X#X I think the first one is the idVendor and the second idProduct but your going to need to do this for each brand of phone/tablet you have.
3) I havent figured out how 51-adb.rules and 99-adb.rules are different or why.
4) maybe try adding "plugdev" group to your user with "usermod -a -G plugdev your_user", Try that at your own risk, though I don't thinks it anyriskier than launching a gui as root but I believe if necessary you should at least use "gksudo eclipse" instead.
I hope that helped clearify some things, the udev rules syntax is a bit of a mystery to me aswell, but from what I hear it can be different for different systems so try some things out, one ate a time, and note what change works.
WebDriver driver;
public void launch(){
driver = new FirefoxDriver();
driver.get("http://www.cleartrip.com/");
driver.manage().window().maximize();
System.out.println("The browser launched successfully");
}
public void clickdate(String inputDate){
WebElement ele =driver.findElement(By.id("DepartDate"));
ele.click();
String month = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[1]")).getText();
String year = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[2]")).getText();
System.out.println("Application month : "+month + " Year :"+year);
int monthNum = getMonthNum(month);
System.out.println("Enum Num : "+monthNum);
String[] parts = inputDate.split("/");
int noOfHits = ((Integer.parseInt(parts[2])-Integer.parseInt(year))*12)+(Integer.parseInt(parts[1])-monthNum);
System.out.println("No OF Hits "+noOfHits);
for(int i=0; i< noOfHits;i++){
driver.findElement(By.className("nextMonth ")).click();
}
List<WebElement> cals=driver.findElements(By.xpath("//div[@class='monthBlock first']//tr"));
System.out.println(cals.size());
for( WebElement daterow : cals){
List<WebElement> datenums = daterow.findElements(By.xpath("//td"));
/*iterating the "td" list*/
for(WebElement date : datenums ){
/* Checking The our input Date(if it match go inside and click*/
if(date.getText().equalsIgnoreCase(parts[0])){
date.click();
break;
}
}
}
}
public int getMonthNum(String month){
for (Month mName : Month.values()) {
if(mName.name().equalsIgnoreCase(month))
return mName.value;
}
return -1;
}
public enum Month{
January(1), February(2), March(3), April(4), May(5), June(6) , July(7), August(8), September(9), October(10), November(11),December(12);
private int value;
private Month(int value) {
this.value = value;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Cleartrip cl=new Cleartrip();
cl.launch();
cl.clickdate("24/11/2015");
}
}
I want to remove the "(", ")", and "-" characters from the string.
You can use the std::remove_if()
algorithm to remove only the characters you specify:
#include <iostream>
#include <algorithm>
#include <string>
bool IsParenthesesOrDash(char c)
{
switch(c)
{
case '(':
case ')':
case '-':
return true;
default:
return false;
}
}
int main()
{
std::string str("(555) 555-5555");
str.erase(std::remove_if(str.begin(), str.end(), &IsParenthesesOrDash), str.end());
std::cout << str << std::endl; // Expected output: 555 5555555
}
The std::remove_if()
algorithm requires something called a predicate, which can be a function pointer like the snippet above.
You can also pass a function object (an object that overloads the function call ()
operator). This allows us to create an even more general solution:
#include <iostream>
#include <algorithm>
#include <string>
class IsChars
{
public:
IsChars(const char* charsToRemove) : chars(charsToRemove) {};
bool operator()(char c)
{
for(const char* testChar = chars; *testChar != 0; ++testChar)
{
if(*testChar == c) { return true; }
}
return false;
}
private:
const char* chars;
};
int main()
{
std::string str("(555) 555-5555");
str.erase(std::remove_if(str.begin(), str.end(), IsChars("()- ")), str.end());
std::cout << str << std::endl; // Expected output: 5555555555
}
You can specify what characters to remove with the "()- "
string. In the example above I added a space so that spaces are removed as well as parentheses and dashes.
This is how we can do it with the new useState
hook.
Method - Pass the state changer function as a props to the child component and do whatever you want to do with the function
import React, {useState} from 'react';
const ParentComponent = () => {
const[state, setState]=useState('');
return(
<ChildConmponent stateChanger={setState} />
)
}
const ChildConmponent = ({stateChanger, ...rest}) => {
return(
<button onClick={() => stateChanger('New data')}></button>
)
}
Put your if condition inside resize
function:
var windowsize = $(window).width();
$(window).resize(function() {
windowsize = $(window).width();
if (windowsize > 440) {
//if the window is greater than 440px wide then turn on jScrollPane..
$('#pane1').jScrollPane({
scrollbarWidth:15,
scrollbarMargin:52
});
}
});
Put and Patch method are similar . But in rails it has different metod If we want to update/replace whole record then we have to use Put method. If we want to update particular record use Patch method.
Create a new keypair: (go with the defaults)
ssh-keygen
Copy the public key to the server: (password for the last time)
ssh-copy-id [email protected]
From now on the server should recognize your key and not ask you for the password anymore:
ssh [email protected]
the answers above were confusing to me. Here is what i did:
the first field "Asset type" must be launcher icons. browse to the file you want as icon, select it and android studio will show you in the same window what it will look like under different resolutions.
choose a different name for it, click next. Now the icon set for all those hdpi, xhdpi, mdpi will be in corresponding mipmap folders
finally, most importantly go to your manifest file and change "android:icon" to the name of your new icon image.
Here is an alternate approach. It is more intuitive.
One key aspect I feel some of the answers did not take into account, which I point out for posterity, is apply() lets you do row calculations easily, but only for matrix (all numeric) data
operations on columns are possible still for dataframes:
as.data.frame(lapply(df, myFunctionForColumn()))
To operate on rows, we make the transpose first.
tdf<-as.data.frame(t(df))
as.data.frame(lapply(tdf, myFunctionForRow()))
The downside is that I believe R will make a copy of your data table. Which could be a memory issue. (This is truly sad, because it is programmatically simple for tdf to just be an iterator to the original df, thus saving memory, but R does not allow pointer or iterator referencing.)
Also, a related question, is how to operate on each individual cell in a dataframe.
newdf <- as.data.frame(lapply(df, function(x) {sapply(x, myFunctionForEachCell()}))
You can define a a click function and then set the onclick
attribute for the element.
function imageClick(url) {
window.location = url;
}
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" onclick="imageClick('../images/bottle.html')" />
This approach lets you get rid of the surrounding <a>
element. If you want to keep it, then define the onclick
attribute on <a>
instead of on <img>
.
If you use the JSON Serializer, you can simply store your object in string format as such
myHiddenText.value = JSON.stringify( myObject );
You can then get the value back with
myObject = JSON.parse( myHiddenText.value );
However, if you're not going to pass this value across page submits, it might be easier for you, and you'll save yourself a lot of serialization, if you just tuck it away as a global javascript variable.
UPDATE
T1
SET
T1.Inci = T2.Inci
FROM
T1
INNER JOIN
T2
ON
T1.Brands = T2.Brands
AND
T1.Category= T2.Category
AND
T1.Date = T2.Date
First Button submits the form and second does not
<body>
<form ng-app="myApp" ng-controller="myCtrl" ng-submit="Sub()">
<div>
S:<input type="text" ng-model="v"><br>
<br>
<button>Submit</button>
//Dont Submit
<button type='button' ng-click="Dont()">Dont Submit</button>
</div>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.Sub=function()
{
alert('Inside Submit');
}
$scope.Dont=function()
{
$scope.v=0;
}
});
</script>
</body>
Using just #
makes some funny movements, so I would recommend to use #self
if you would like to save on typing efforts of JavaScript bla, bla,
.
Make sure docker is running in your local machine. build command will work but its required running docker to get network data.
I think it will help.
I believe that aspect ratio is width divided by height.
r = w/h
OK, here are the things that come into mind:
my WCF web service calls another ASMX web service, installed on a **different** web server
Ntlm
to Windows
and test again.OK, a few words on impersonation. Basically it is a known issue that you cannot use the impersonation tokens that you got to one server, to pass to another server. The reason seems to be that the token is a kind of a hash using user's password and valid for the machine generated from so it cannot be used from the middle server.
Delegation is possible under WCF (i.e. forwarding impersonation from a server to another server). Look at this topic here.
You can compress the bitmap as an byte's array and then uncompress it in another activity, like this.
Compress!!
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
setresult.putExtra("BMP",bytes);
Uncompress!!
byte[] bytes = data.getByteArrayExtra("BMP");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
If by "hex data" you mean a string of the form
s = "6a48f82d8e828ce82b82"
you can use
i = int(s, 16)
to convert it to an integer and
str(i)
to convert it to a decimal string.
I wouldn't do it. Use virtual PCs instead. It might take a little setup, but you'll thank yourself in the long run. In my experience, you can't really get them cleanly installed side by side and unless they are standalone installs you can't really verify that it is 100% true-to-browser rendering.
Update: Looks like one of the better ways to accomplish this (if running Windows 7) is using Windows XP mode to set up multiple virtual machines: Testing Multiple Versions of IE on one PC at the IEBlog.
Update 2: (11/2014) There are new solutions since this was last updated. Microsoft now provides VMs for any environment to test multiple versions of IE: Modern.IE
It depends on your application. There are some considerations:
The Miller-Rabin and analogue tests are only faster than a sieve for numbers over a certain size (somewhere around a few million, I believe). Below that, using a trial division (if you just have a few numbers) or a sieve is faster.
you are having the FindOpenSSL.cmake file in the cmake module(path usr/shared.cmake-3.5/modules) # Search OpenSSL
find_package(OpenSSL REQUIRED)
if( OpenSSL_FOUND )
include_directories(${OPENSSL_INCLUDE_DIRS})
link_directories(${OPENSSL_LIBRARIES})
message(STATUS "Using OpenSSL ${OPENSSL_VERSION}")
target_link_libraries(project_name /path/of/libssl.so /path/of/libcrypto.so)
Configuring the CORS response headers on the server wasn't really an option. You should configure a proxy in client side.
Sample to Angular - So, I created a proxy.conf.json file to act as a proxy server. Below is my proxy.conf.json file:
{
"/api": {
"target": "http://localhost:49389",
"secure": true,
"pathRewrite": {
"^/api": "/api"
},
"changeOrigin": true
}
}
Put the file in the same directory the package.json then I modified the start command in the package.json file like below
"start": "ng serve --proxy-config proxy.conf.json"
now, the http call from the app component is as follows:
return this.http.get('/api/customers').map((res: Response) => res.json());
Lastly to run use npm start or ng serve --proxy-config proxy.conf.json
If you're set on using scanf
, you can do something like the following:
int val;
char follow;
int read = scanf( "%d%c", &val, &follow );
if ( read == 2 )
{
if ( isspace( follow ) )
{
// input is an integer followed by whitespace, accept
}
else
{
// input is an integer followed by non-whitespace, reject
}
}
else if ( read == 1 )
{
// input is an integer followed by EOF, accept
}
else
{
// input is not an integer, reject
}
The Control class has HorizontalContentAlignment and VerticalContentAlignment properties. These properties determine how a control’s content fills the space within the control.
Set HorizontalContentAlignment and VerticalContentAlignment to Center.
SELECT
AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit,
BillLimit, Mode, PNotes, gtab82.memno
FROM
VCustomer AS v1
INNER JOIN
gtab82 ON gtab82.memacid = v1.AcId
WHERE (AcGrCode = '204' OR CreDebt = 'True')
AND Masked = 'false'
ORDER BY AcName
You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer
but only use it in the ON
clause for uncertain reasons. You may want to review that aspect of your code.
The Perl documentation comes with a nice collection of FAQs. Your question is frequently asked:
% perldoc -q duplicate
The answer, copy and pasted from the output of the command above, appears below:
Found in /usr/local/lib/perl5/5.10.0/pods/perlfaq4.pod How can I remove duplicate elements from a list or array? (contributed by brian d foy) Use a hash. When you think the words "unique" or "duplicated", think "hash keys". If you don't care about the order of the elements, you could just create the hash then extract the keys. It's not important how you create that hash: just that you use "keys" to get the unique elements. my %hash = map { $_, 1 } @array; # or a hash slice: @hash{ @array } = (); # or a foreach: $hash{$_} = 1 foreach ( @array ); my @unique = keys %hash; If you want to use a module, try the "uniq" function from "List::MoreUtils". In list context it returns the unique elements, preserving their order in the list. In scalar context, it returns the number of unique elements. use List::MoreUtils qw(uniq); my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7 my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7 You can also go through each element and skip the ones you've seen before. Use a hash to keep track. The first time the loop sees an element, that element has no key in %Seen. The "next" statement creates the key and immediately uses its value, which is "undef", so the loop continues to the "push" and increments the value for that key. The next time the loop sees that same element, its key exists in the hash and the value for that key is true (since it's not 0 or "undef"), so the next skips that iteration and the loop goes to the next element. my @unique = (); my %seen = (); foreach my $elem ( @array ) { next if $seen{ $elem }++; push @unique, $elem; } You can write this more briefly using a grep, which does the same thing. my %seen = (); my @unique = grep { ! $seen{ $_ }++ } @array;
we can use data.table library
library(data.table)
expr <- data.table(expr)
expr[cell_type == "hesc"]
expr[cell_type %in% c("hesc","fibroblast")]
or filter using %like%
operator for pattern matching
expr[cell_type %like% "hesc"|cell_type %like% "fibroblast"]
RaYell's answer is good - it answers your question.
It seems to me though that you should really be creating an object keyed by labels with sub-objects as values:
var columns = {};
for (var i = 0; i < oFullResponse.results.length; i++) {
var key = oFullResponse.results[i].label;
columns[key] = {
sortable: true,
resizeable: true
};
}
// Now you can access column info like this.
columns['notes'].resizeable;
The above approach should be much faster and idiomatic than searching the entire object array for a key for each access.
If you are using a LinearLayout
you should call myView.bringToFront()
and after you should call parentView.requestLayout()
and parentView.invalidate()
to force the parent to redraw with the new child order.
This worked for me:
.table tbody tr:hover td, .table tbody tr:hover th {
background-color: #eeeeea;
}
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
You can create custom CSS tooltips using a data attribute, pseudo elements and content: attr()
eg.
http://jsfiddle.net/clintioo/gLeydk0k/11/
<div data-tooltip="This is my tooltip">
<label>Name</label>
<input type="text" />
</div>
.
div:hover:before {
content: attr(data-tooltip);
position: absolute;
padding: 5px 10px;
margin: -3px 0 0 180px;
background: orange;
color: white;
border-radius: 3px;
}
div:hover:after {
content: '';
position: absolute;
margin: 6px 0 0 3px;
width: 0;
height: 0;
border-top: 5px solid transparent;
border-right: 10px solid orange;
border-bottom: 5px solid transparent;
}
input[type="text"] {
width: 125px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
inspired by @jason-bunting, same thing for either height or width:
function resizeElementDimension(element, doHeight) {
dim = (doHeight ? 'Height' : 'Width')
ref = (doHeight ? 'Top' : 'Left')
var x = 0;
var body = window.document.body;
if(window['inner' + dim])
x = window['inner' + dim]
else if (body.parentElement['client' + dim])
x = body.parentElement['client' + dim]
else if (body && body['client' + dim])
x = body['client' + dim]
element.style[dim.toLowerCase()] = ((x - element['offset' + ref]) + "px");
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ChnagePassword.aspx/AutocompleteSuggestions",
data: "{'searchstring':'" + request.term + "','st':'Arb'}",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
return { value: item }
}))
},
error: function (result) {
alert("Error");
}
});
Here is a link to a shorter and to the point description: http://www.granneman.com/webdev/editors/sublime-text/packages/how-to-install-and-use-package-control/
The steps are:
Here is my working solution :
// --------------------------
// SOAP Message creation
// --------------------------
SOAPMessage sm = MessageFactory.newInstance().createMessage();
sm.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
sm.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
SOAPPart sp = sm.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
se.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
se.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
SOAPBody sb = sm.getSOAPBody();
//
// Add all input fields here ...
//
SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
// -----------------------------------
// URL creation with TimeOut connexion
// -----------------------------------
URL endpoint = new URL(null,
"http://myDomain/myWebService.php",
new URLStreamHandler() { // Anonymous (inline) class
@Override
protected URLConnection openConnection(URL url) throws IOException {
URL clone_url = new URL(url.toString());
HttpURLConnection clone_urlconnection = (HttpURLConnection) clone_url.openConnection();
// TimeOut settings
clone_urlconnection.setConnectTimeout(10000);
clone_urlconnection.setReadTimeout(10000);
return(clone_urlconnection);
}
});
try {
// -----------------
// Send SOAP message
// -----------------
SOAPMessage retour = connection.call(sm, endpoint);
}
catch(Exception e) {
if ((e instanceof com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl) && (e.getCause()!=null) && (e.getCause().getCause()!=null) && (e.getCause().getCause().getCause()!=null)) {
System.err.println("[" + e + "] Error sending SOAP message. Initial error cause = " + e.getCause().getCause().getCause());
}
else {
System.err.println("[" + e + "] Error sending SOAP message.");
}
}
There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:
http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html
As long as your program's in a sane state, you can also call (void)puts(your_string)
to print it to stdout. Same principle applies to all functions available to the debugger, actually.
In my case, my website's output path is changed by somebody, the IIS Express even not load OWIN, and the setup class will not be hit of course. After I set the output path as "bin\", it works well.
You have to increase client_max_body_size in nginx.conf
file. This is the basic step. But if your backend laravel
then you have to do some changes in the php.ini
file as well. It depends on your backend. Below I mentioned file location and condition name.
sudo vim /etc/nginx/nginx.conf.
After open the file adds this into HTTP section.
client_max_body_size 100M;
You need to do a couple of things to use the library:
Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2
Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.
You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.
After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)
Cheers!
EDIT
Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.
See String formatting in C# for some example uses of String.Format
Actually a better example of formatting int
String.Format("{0:00000}", 15); // "00015"
or use String Interpolation:
$"{15:00000}"; // "00015"
Example for insert into values in One database table into another database table
insert into dbo.onedatabase.FolderStatus
(
[FolderStatusId],
[code],
[title],
[last_modified]
)
select [FolderStatusId], [code], [title], [last_modified]
from dbo.Twodatabase.f_file_stat
$ pip install pickle5
import pickle5 as pickle
pb = pickle.PickleBuffer(b"foo")
data = pickle.dumps(pb, protocol=5)
assert pickle.loads(data) == b"foo"
This package backports all features and APIs added in the pickle module in Python 3.8.3, including the PEP 574 additions. It should work with Python 3.5, 3.6 and 3.7.
Basic usage is similar to the pickle module, except that the module to be imported is pickle5:
Cause you need to add jQuery library to your file:
jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.
<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>
# check out all files in <paths> from branch <branch_name>
git checkout <branch_name> -- <paths>
Source: http://nicolasgallagher.com/git-checkout-specific-files-from-another-branch/.
See also man git checkout
.
Examples:
# Check out "somefile.c" from branch `my_branch`
git checkout my_branch -- somefile.c
# Check out these 4 files from `my_branch`
git checkout my_branch -- file1.h file1.cpp mydir/file2.h mydir/file2.cpp
# Check out ALL files from my_branch which are in
# directory "path/to/dir"
git checkout my_branch -- path/to/dir
If you don't specify, the branch_name
it is automatically assumed to be HEAD
, which is your most-recent commit of the currently-checked-out branch. So, you can also just do this to check out "somefile.c" and have it overwrite any local, uncommitted changes:
# Check out "somefile.c" from `HEAD`, to overwrite any local, uncommitted
# changes
git checkout -- somefile.c
# Or check out a whole folder from `HEAD`:
git checkout -- some_directory
git checkout --
in my answer here: Who is "us" and who is "them" according to Git?.It's also possible to set both the From name and from address using something like:
echo test | mail -s "test" [email protected] -- -F'Some Name<[email protected]>' -t
For some reason passing -F'Some Name'
and [email protected]
doesn't work, but passing in the -t
to sendmail works and is "easy".
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();
dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);
document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script src="https://momentjs.com/downloads/moment.js"></script>
</body>
</html>
_x000D_
Not every language supports reflection, but the principles are usually the same in languages that support it.
Reflection is the ability to "reflect" on the structure of your program. Or more concrete. To look at the objects and classes you have and programmatically get back information on the methods, fields, and interfaces they implement. You can also look at things like annotations.
It's useful in a lot of situations. Everywhere you want to be able to dynamically plug in classes into your code. Lots of object relational mappers use reflection to be able to instantiate objects from databases without knowing in advance what objects they're going to use. Plug-in architectures is another place where reflection is useful. Being able to dynamically load code and determine if there are types there that implement the right interface to use as a plugin is important in those situations.
If after the installation curl-dev luarocks does not see the headers:
find /usr -name 'curl.h'
Example: /usr/include/x86_64-linux-gnu/curl/curl.h
luarocks install lua-cURL CURL_INCDIR=/usr/include/x86_64-linux-gnu/
Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.
The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks
<context:annotation-config>
declares support for general annotations such as @Required
, @Autowired
, @PostConstruct
, and so on.
<mvc:annotation-driven />
declares explicit support for annotation-driven MVC controllers (i.e. @RequestMapping
, @Controller
, although support for those is the default behaviour), as well as adding support for declarative validation via @Valid
and message body marshalling with @RequestBody
/ResponseBody
.
I downloaded a project from github with .idea folder. After deleting that folder, everything was ok.
Linear regression output as probabilities
It's tempting to use the linear regression output as probabilities but it's a mistake because the output can be negative, and greater than 1 whereas probability can not. As regression might actually produce probabilities that could be less than 0, or even bigger than 1, logistic regression was introduced.
Source: http://gerardnico.com/wiki/data_mining/simple_logistic_regression
Outcome
In linear regression, the outcome (dependent variable) is continuous. It can have any one of an infinite number of possible values.
In logistic regression, the outcome (dependent variable) has only a limited number of possible values.
The dependent variable
Logistic regression is used when the response variable is categorical in nature. For instance, yes/no, true/false, red/green/blue, 1st/2nd/3rd/4th, etc.
Linear regression is used when your response variable is continuous. For instance, weight, height, number of hours, etc.
Equation
Linear regression gives an equation which is of the form Y = mX + C, means equation with degree 1.
However, logistic regression gives an equation which is of the form Y = eX + e-X
Coefficient interpretation
In linear regression, the coefficient interpretation of independent variables are quite straightforward (i.e. holding all other variables constant, with a unit increase in this variable, the dependent variable is expected to increase/decrease by xxx).
However, in logistic regression, depends on the family (binomial, Poisson, etc.) and link (log, logit, inverse-log, etc.) you use, the interpretation is different.
Error minimization technique
Linear regression uses ordinary least squares method to minimise the errors and arrive at a best possible fit, while logistic regression uses maximum likelihood method to arrive at the solution.
Linear regression is usually solved by minimizing the least squares error of the model to the data, therefore large errors are penalized quadratically.
Logistic regression is just the opposite. Using the logistic loss function causes large errors to be penalized to an asymptotically constant.
Consider linear regression on categorical {0, 1} outcomes to see why this is a problem. If your model predicts the outcome is 38, when the truth is 1, you've lost nothing. Linear regression would try to reduce that 38, logistic wouldn't (as much)2.
Looking at the screen from the top, you get x and z axis.
Looking at the screen from the side, you get y and z axis.
Calculate the focal lengths of the top and side views, using trigonometry, which is the distance between the eye and the middle of the screen, which is determined by the field of view of the screen. This makes the shape of two right triangles back to back.
hw = screen_width / 2
hh = screen_height / 2
fl_top = hw / tan(?/2)
fl_side = hh / tan(?/2)
Then take the average focal length.
fl_average = (fl_top + fl_side) / 2
Now calculate the new x and new y with basic arithmetic, since the larger right triangle made from the 3d point and the eye point is congruent with the smaller triangle made by the 2d point and the eye point.
x' = (x * fl_top) / (z + fl_top)
y' = (y * fl_top) / (z + fl_top)
Or you can simply set
x' = x / (z + 1)
and
y' = y / (z + 1)
$ch = curl_init('http://api.imgur.com/2/upload.xml'); //initialising our url
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //used for https headers
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //used for https headers
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($pvars));
//the value we post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //waiting for reponse, default value in php is zero ie, curls normally do not wait for a response
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
$output = curl_exec($ch); //the real execution
curl_close($ch);
echo $output;
Try this code. I am not sure about it. But i used it to send xml data to a remote url.
I have found that this error can occur in DESIGN MODE as opposed to ? execution mode... If you are doing something such as creating a class member which requires access to an .INI or .HTM file (configuration file, help file) you might want to NOT initialize the item in the declaration, but initialize it later in FORM_Load() etc... When you DO initialize... Use a guard IF statement:
/// <summary>FORM: BasicApp - Load</summary>
private void BasicApp_Load(object sender, EventArgs e)
{
// Setup Main Form Caption with App Name and Config Control Info
if (!DesignMode)
{
m_Globals = new Globals();
Text = TGG.GetApplicationConfigInfo();
}
}
This will keep the MSVS Designer from trying to create an INI or HTM file when you are in design mode.
A completely different approach:
<button type="submit">
in the form will be activated on pressing Enter.style="display:none;
false
, which aborts the submission process.<button type=submit>
to submit the form. Just return true
to cascade the submission.<textarea>
or other form controls will behave as normal.<input>
form controls will trigger the first <button type=submit>
, which returns false
, and thus nothing happens.Thus:
<form action="...">
<!-- insert this next line immediately after the <form> opening tag -->
<button type=submit onclick="return false;" style="display:none;"></button>
<!-- everything else follows as normal -->
<!-- ... -->
<button type=submit>Submit</button>
</form>
Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:
Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)
Type command git init
Type command git add --all
Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO
)
Type command git commit -m "my first commit"
Type command git push -u origin master
Note: if you get error unable to detect email or name, just type following commands after 5th step:
git config --global user.email "yourEmail" #your email at Bitbucket
git config --global user.name "yourName" #your name at Bitbucket
Setup https://docs.djangoproject.com/en/dev/topics/logging/ and then these error's will echo where you point them. By default they tend to go off in the weeds so I always start off with a good logging setup before anything else.
Here is a really good example for a basic setup: https://ian.pizza/b/2013/04/16/getting-started-with-django-logging-in-5-minutes/
Edit: The new link is moved to: https://github.com/ianalexander/ianalexander/blob/master/content/blog/getting-started-with-django-logging-in-5-minutes.html
What you've got (according to the debug image) is an object array containing a string array. So you need something like:
Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];
You haven't shown the type of values
- if this is already Object[]
then you could just use (String[])values[0]
.
Of course even with the cast to Object[]
you could still do it in one statement, but it's ugly:
String[] strings = (String[]) ((Object[])values)[0];
The MOST IMPORTANT THING I didn't understand for quite awhile is that the request MUST contain "callback=JSON_CALLBACK", because AngularJS modifies the request url, substituting a unique identifier for "JSON_CALLBACK". The server response must use the value of the 'callback' parameter instead of hard coding "JSON_CALLBACK":
JSON_CALLBACK(json_response); // wrong!
Since I was writing my own PHP server script, I thought I knew what function name it wanted and didn't need to pass "callback=JSON_CALLBACK" in the request. Big mistake!
AngularJS replaces "JSON_CALLBACK" in the request with a unique function name (like "callback=angular.callbacks._0"), and the server response must return that value:
angular.callbacks._0(json_response);
I thought I'd drop my two cents on this: this is one of those operations that should always be purely functional, not relying on any external variables. A few already gave a good answer, using reduce
is the way to go here.
Since most of us can already afford to use ES2015 syntax, here's my proposition:
const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);
We're making it an immutable function while we're at it. What reduce
is doing here is simply this:
Start with a value of 0
for the accumulator, and add the value of the current looped item to it.
Yay for functional programming and ES2015! :)
Yes, s
stands for string. The json.loads
function does not take the file path, but the file contents as a string. Look at the documentation at https://docs.python.org/2/library/json.html!
There are two easy and safe rules which work not only in sh
but also bash
.
This works for all chars except single quote itself. To escape the single quote, close the quoting before it, insert the single quote, and re-open the quoting.
'I'\''m a s@fe $tring which ends in newline
'
sed command: sed -e "s/'/'\\\\''/g; 1s/^/'/; \$s/\$/'/"
This works for all characters except newline. For newline characters use single or double quotes. Empty strings must still be handled - replace with ""
\I\'\m\ \a\ \s\@\f\e\ \$\t\r\i\n\g\ \w\h\i\c\h\ \e\n\d\s\ \i\n\ \n\e\w\l\i\n\e"
"
sed command: sed -e 's/./\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'
.
There's an easy safe set of characters, like [a-zA-Z0-9,._+:@%/-]
, which can be left unescaped to keep it more readable
I\'m\ a\ s@fe\ \$tring\ which\ ends\ in\ newline"
"
sed command: LC_ALL=C sed -e 's/[^a-zA-Z0-9,._+@%/-]/\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'
.
Note that in a sed program, one can't know whether the last line of input ends with a newline byte (except when it's empty). That's why both above sed commands assume it does not. You can add a quoted newline manually.
Note that shell variables are only defined for text in the POSIX sense. Processing binary data is not defined. For the implementations that matter, binary works with the exception of NUL bytes (because variables are implemented with C strings, and meant to be used as C strings, namely program arguments), but you should switch to a "binary" locale such as latin1.
(You can easily validate the rules by reading the POSIX spec for sh
. For bash, check the reference manual linked by @AustinPhillips)
document.getElementById("something").innerHTML = "<img src=\"something\" onmouseover=\"change('ex1')\" />";
OR
document.getElementById("something").innerHTML = '<img src="something" onmouseover="change(\'ex1\')" />';
It should be working...
As far as I know it's not possible... but you can try something like this:
.underline _x000D_
{_x000D_
color: blue;_x000D_
border-bottom: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
<span class="underline">hello world</span>_x000D_
</div>
_x000D_
You should use
<input type="submit" value="submit" />
inside your form
.
and add action
into your form
tag for example:
<form action="booking.php" method="post">
It's post your form into action which you choose.
From php you can get this value by
$_POST['booking-check'];
string cmdArguments = $@"/k svn log --trust-server-cert --non-interactive ""{servidor}"" --username alex --password alex -r {numeroRevisao}";
ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe", cmdArguments);
cmd.CreateNoWindow = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.WindowStyle = ProcessWindowStyle.Hidden;
cmd.UseShellExecute = false;
Process reg = Process.Start(cmd);
string output = "";
using (System.IO.StreamReader myOutput = reg.StandardOutput)
{
output += myOutput.ReadToEnd();
}
using (System.IO.StreamReader myError = reg.StandardError)
{
output += myError.ReadToEnd();
}
return output;
If you want numbers from 1 up to 100:
100|[1-9]\d?
in my case: invalidateOptionsMenu
just re-setted the text to the original one,
but directly accessing the menu item and re-writing the desire text worked without problems:
if (mnuTopMenuActionBar_ != null) {
MenuItem mnuPageIndex = mnuTopMenuActionBar_
.findItem(R.id.menu_magazin_pageOfPage_text);
if (mnuPageIndex != null) {
if (getScreenOrientation() == 1) {
mnuPageIndex.setTitle((i + 1) + " von " + pages);
}
else {
mnuPageIndex.setTitle(
(i + 1) + " + " + (i + 2) + " " + " von " + pages);
}
// invalidateOptionsMenu();
}
}
due to the comment below, I was able to access the menu item via the following code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.magazine_swipe_activity, menu);
mnuTopMenuActionBar_ = menu;
return true;
}
I haven't tried it myself, but I would suggest using Jest's toThrow assertion. So I guess your example would look something like this:
it('should throw Error with message \'UNKNOWN ERROR\' when no parameters were passed', (t) => {
const error = t.throws(() => {
throwError();
}, TypeError);
expect(t).toThrowError('UNKNOWN ERROR');
//or
expect(t).toThrowError(TypeError);
});
Again, I haven't test it, but I think it should work.
First, one of Perlis's epigrams:
"If you have a procedure with 10 parameters, you probably missed some."
Some of the 10 arguments are presumably related. Group them into an object, and pass that instead.
Making an example up, because there's not enough information in the question to answer directly:
class PersonInfo(object):
def __init__(self, name, age, iq):
self.name = name
self.age = age
self.iq = iq
Then your 10 argument function:
def f(x1, x2, name, x3, iq, x4, age, x5, x6, x7):
...
becomes:
def f(personinfo, x1, x2, x3, x4, x5, x6, x7):
...
and the caller changes to:
personinfo = PersonInfo(name, age, iq)
result = f(personinfo, x1, x2, x3, x4, x5, x6, x7)
Check the type
property. Would that suffice?
You also can do it with functional programming:
from functools import reduce
reduce(lambda df1, df2: df1.merge(df2, "outer"), mydfs)
I also met the error message in raspberry pi 3, but my solution is reload kernel of camera after search on google, hope it can help you.
sudo modprobe bcm2835-v4l2
BTW, for this error please check your camera and file path is workable or not
I am using this from PowerShell:
dir -directory -name -recurse > list_my_folders.txt
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
Or, if you insist on making work for yourself...
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(myByteArray);
//fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.
Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.
Just in case anyone comes looking a solution for this problem.
The Authentication problems can be alleviated by activating the google 2-step verification for the account in use and creating an app specific password. I had the same problem as the OP. Enabling 2-step worked.
Example 2012:
library("xlsx")
FirstTable <- read.xlsx("MyExcelFile.xlsx", 1 , stringsAsFactors=F)
SecondTable <- read.xlsx("MyExcelFile.xlsx", 2 , stringsAsFactors=F)
Example 2015:
library("readxl")
FirstTable <- read_excel("MyExcelFile.xlsx", 1)
SecondTable <- read_excel("MyExcelFile.xlsx", 2)
readxl
and have made good experience with it.I doubt anything is killing the process just because it takes a long time. Killed generically means something from the outside terminated the process, but probably not in this case hitting Ctrl-C since that would cause Python to exit on a KeyboardInterrupt exception. Also, in Python you would get MemoryError exception if that was the problem. What might be happening is you're hitting a bug in Python or standard library code that causes a crash of the process.
The "delete module-info.java at your Project Explorer tab" answer is the easiest and most straightforward answer, but
for those who would want a little more understanding or control of what's happening, the following alternate methods may be desirable;
or
For those who use Data Binding:
Add the following static method to any class
@BindingAdapter("app:thumbTintCompat")
public static void setThumbTint(SeekBar seekBar, @ColorInt int color) {
seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
Add app:thumbTintCompat
attribute to your SeekBar
<SeekBar
android:id="@+id/seek_bar"
style="@style/Widget.AppCompat.SeekBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:thumbTintCompat="@{@android:color/white}"
/>
That's it. Now you can use app:thumbTintCompat
with any SeekBar
. The progress tint can be configured in the same way.
Note: this method is also compatble with pre-lollipop devices.
For arbitaray range of month numbers
month_integer=range(0,100)
map(lambda x: calendar.month_name[x%12+start],month_integer)
will yield correct list. Adjust start
-parameter from where January begins in the month-integer list.
My gem version 2.0.3 and I was getting the same issue. This command resolved it:
gem install json --platform=ruby --verbose
It is now officially supported by Facebook. Just select the 'Button' layout.
Try this:
This function resizes a bitmap proportionally. When the last parameter is set to "X" the newDimensionXorY
is treated as s new width and when set to "Y" a new height.
public Bitmap getProportionalBitmap(Bitmap bitmap,
int newDimensionXorY,
String XorY) {
if (bitmap == null) {
return null;
}
float xyRatio = 0;
int newWidth = 0;
int newHeight = 0;
if (XorY.toLowerCase().equals("x")) {
xyRatio = (float) newDimensionXorY / bitmap.getWidth();
newHeight = (int) (bitmap.getHeight() * xyRatio);
bitmap = Bitmap.createScaledBitmap(
bitmap, newDimensionXorY, newHeight, true);
} else if (XorY.toLowerCase().equals("y")) {
xyRatio = (float) newDimensionXorY / bitmap.getHeight();
newWidth = (int) (bitmap.getWidth() * xyRatio);
bitmap = Bitmap.createScaledBitmap(
bitmap, newWidth, newDimensionXorY, true);
}
return bitmap;
}
What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.
There is also a shorter form for $(document).ready(function(){...})
in $(function(){...})
.
So, this is all you need:
$(function(){
$('div.easy_editor').css('border','9px solid red');
});
If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:
$(function(){
$('.easy_editor').css('border','9px solid red');
});
This will work, independent of Excel version (2003, 2007, 2010). The first has 65536 rows in a sheet, while the latter two have a million rows or so. Sheet1.Rows.Count
returns this number dependent on the version.
numofrows = Sheet1.Range("A1").Offset(Sheet1.Rows.Count - 1, 0).End(xlUp).Row
or the equivalent but shorter
numofrows = Sheet1.Cells(Sheet1.Rows.Count,1).End(xlUp)
This searches up from the bottom of column A for the first non-empty cell, and gets its row number.
This also works if you have data that go further down in other columns. So for instance, if you take your example data and also write something in cell FY4763, the above will still correctly return 9 (not 4763, which any method involving the UsedRange
property would incorrectly return).
Note that really, if you want the cell reference, you should just use the following. You don't have to first get the row number, and then build the cell reference.
Set rngLastCell = Sheet1.Range("A1").Offset(Sheet1.Rows.Count - 1, 0).End(xlUp)
Note that this method fails in certain edge cases:
So watch out if you're planning to use row 1,048,576 for these things!
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1","value1");
String query = URLEncodedUtils.format(params, "utf-8");
URI url = URIUtils.createURI(scheme, userInfo, authority, port, path, query, fragment); //can be null
HttpGet httpGet = new HttpGet(url);
Note: url = new URI(...)
is buggy
I figured out how to do this. I was building an application very similar to the example/tutorial you discussed in your original question.
Here's a snippet of the code that worked for me:
int pageSize = 4;
int pageNumber = (page ?? 1);
//Used the following two formulas so that it doesn't round down on the returned integer
decimal totalPages = ((decimal)(viewModel.Teachers.Count() /(decimal) pageSize));
ViewBag.TotalPages = Math.Ceiling(totalPages);
//These next two functions could maybe be reduced to one function....would require some testing and building
viewModel.Teachers = viewModel.Teachers.ToPagedList(pageNumber, pageSize);
ViewBag.OnePageofTeachers = viewModel.Teachers;
ViewBag.PageNumber = pageNumber;
return View(viewModel);
I added
using.PagedList;
to my controller as the tutorial states.
Now in my view my using statements etc at the top, NOTE i didnt change my using model statement.
@model CSHM.ViewModels.TeacherIndexData
@using PagedList;
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
and then at the bottom to build my paged list I used the following and it seems to work. I haven't yet built in the functionality for current sort, showing related data, filters, etc but i dont think it will be that difficult.
Page @ViewBag.PageNumber of @ViewBag.TotalPages
@Html.PagedListPager((IPagedList)ViewBag.OnePageofTeachers, page => Url.Action("Index", new { page }))
Hope that works for you. Let me know if it works!!
C++11 brought us lambdas, which can be incredibly useful in this situation:
#define MACRO(X,Y) \
[&](x_, y_) { \
cout << "1st arg is:" << x_ << endl; \
cout << "2nd arg is:" << y_ << endl; \
cout << "Sum is:" << (x_ + y_) << endl; \
}((X), (Y))
You keep the generative power of macros, but have a comfy scope from which you can return whatever you want (including void
). Additionally, the issue of evaluating macro parameters multiple times is avoided.
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
In css add this to the element:
margin-top: -15px; /*for exact positioning */
margin-top: -5%; /* for relative positioning */
you can use either one to position accordingly.
setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.
CODE:
var im = document.getElementById("img");
var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;
function changeImage()
{
im.setAttribute("src", images[index]);
index++;
if(index >= images.length)
{
index=0;
}
}
setInterval(changeImage, 30000);
Since Django 2.x, on_delete
is required.
Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.
Personally, I'd append the element to the form instead of hacking the serialized data, e.g.
moredata = 'your custom data here';
// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);
// append to the form
$('#myForm').append($input);
// then..
data: $('#myForm').serialize()
That way, you don't have to worry about ?
or &
Use jQuery....I know you say you're trying to teach someone javascript, but teach him a cleaner technique... for instance, I could:
<select id="navigation">
<option value="unit_01.htm">Unit 1</option>
<option value="#5.2">Bookmark 2</option>
</select>
And with a little jQuery, you could do:
$("#navigation").change(function()
{
document.location.href = $(this).val();
});
Unobtrusive, and with clean separation of logic and UI.
Necromancing.
It looks you have just as good a schema to work with as me...
Here is how to do it correctly:
In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID
-- First, chech if the table exists...
IF 0 < (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
-- Check for NULL values in the primary-key column
IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
BEGIN
ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL
-- No, don't drop, FK references might already exist...
-- Drop PK if exists
-- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name
--DECLARE @pkDropCommand nvarchar(1000)
--SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
--WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
--AND TABLE_SCHEMA = 'dbo'
--AND TABLE_NAME = 'T_SYS_Language_Forms'
----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
--))
---- PRINT @pkDropCommand
--EXECUTE(@pkDropCommand)
-- Instead do
-- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';
-- Check if they keys are unique (it is very possible they might not be)
IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
BEGIN
-- If no Primary key for this table
IF 0 =
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
-- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
)
ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
;
-- Adding foreign key
IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms')
ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID);
END -- End uniqueness check
ELSE
PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...'
END -- End NULL check
ELSE
PRINT 'FSCK, need to figure out how to update NULL value(s)...'
END
After ton of time to survey,
Finally, I use invokeAll
method of ExecutorService
to solve this problem.
That will strictly interrupt the task while task running.
Here is example
ExecutorService executorService = Executors.newCachedThreadPool();
try {
List<Callable<Object>> callables = new ArrayList<>();
// Add your long time task (callable)
callables.add(new VaryLongTimeTask());
// Assign tasks for specific execution timeout (e.g. 2 sec)
List<Future<Object>> futures = executorService.invokeAll(callables, 2000, TimeUnit.MILLISECONDS);
for (Future<Object> future : futures) {
// Getting result
}
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.shutdown();
The pro is you can also submit ListenableFuture
at the same ExecutorService
.
Just slightly change the first line of code.
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
ListeningExecutorService
is the Listening feature of ExecutorService
at google guava project (com.google.guava) )
If the list is fixed in the script, I like the following the best:
validate() {
grep -F -q -x "$1" <<EOF
item 1
item 2
item 3
EOF
}
Then use validate "$x"
to test if $x
is allowed.
If you want a one-liner, and don't care about whitespace in item names, you can use this (notice -w
instead of -x
):
validate() { echo "11 22 33" | grep -F -q -w "$1"; }
Notes:
sh
compliant.validate
does not accept substrings (remove the -x
option to grep if you want that).validate
interprets its argument as a fixed string, not a regular
expression (remove the -F
option to grep if you want that).Sample code to exercise the function:
for x in "item 1" "item2" "item 3" "3" "*"; do
echo -n "'$x' is "
validate "$x" && echo "valid" || echo "invalid"
done
You should be able to call print("yo!") since there is a constructor for std::string which takes a const char*. These single argument constructors define implicit conversions from their aguments to their class type (unless the constructor is declared explicit which is not the case for std::string). Have you actually tried to compile this code?
void print(std::string input)
{
cout << input << endl;
}
int main()
{
print("yo");
}
It compiles fine for me in GCC. However, if you declared print like this void print(std::string& input)
then it would fail to compile since you can't bind a non-const reference to a temporary (the string would be a temporary constructed from "yo")
the string in your question is not a valid json string. From json.org website:
JSON is built on two structures:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. * An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Basically a json string will always start with either { or [.
Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.
IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.
private
doesn't seem to work if you are defining a method on an explicit object (in your case self
). You can use private_class_method
to define class methods as private (or like you described).
class Person
def self.get_name
persons_name
end
def self.persons_name
"Sam"
end
private_class_method :persons_name
end
puts "Hey, " + Person.get_name
puts "Hey, " + Person.persons_name
Alternatively (in ruby 2.1+), since a method definition returns a symbol of the method name, you can also use this as follows:
class Person
def self.get_name
persons_name
end
private_class_method def self.persons_name
"Sam"
end
end
puts "Hey, " + Person.get_name
puts "Hey, " + Person.persons_name
#
#------------------------------------------------------------------------------
# purpose: to run a command, log cmd output, exit on error
# usage:
# set -e; do_run_cmd_or_exit "$cmd" ; set +e
#------------------------------------------------------------------------------
do_run_cmd_or_exit(){
cmd="$@" ;
do_log "DEBUG running cmd or exit: \"$cmd\""
msg=$($cmd 2>&1)
export exit_code=$?
# If occurred during the execution, exit with error
error_msg="Failed to run the command:
\"$cmd\" with the output:
\"$msg\" !!!"
if [ $exit_code -ne 0 ] ; then
do_log "ERROR $msg"
do_log "FATAL $msg"
do_exit "$exit_code" "$error_msg"
else
# If no errors occurred, just log the message
do_log "DEBUG : cmdoutput : \"$msg\""
fi
}
um responsive is simple
display:table-cell
max-width:700px
do {display:block; width:100%; clear:both}
and that's it no absolute divs ever; divs needs to be 100% then max-width: - desired width -
for inner framming. A true responsive sites has less than 9 lines of css anything passed that you are in a world of shit and over complicated things.
PS : reset.css
style sheets are what makes css blinds there was a logical reason why they gave default styles in the first place.
i had to install android studio in 2 machines and ive solved this problem intalling samnsung kies, i use 3 diferents samnsung devices (plus some other of my family and friends) and i dont have to strugle with the drivers, it works for me and i recomend it. hope it helps
For Android Studio 1.4, I had to do the following ...
In the project explorer window, open the "Gradle Scripts" folder.
Edit the gradle.properties file.
Append the following to the bottom, replacing the below values with your own where appropriate ...
systemProp.http.proxyHost=?.?.?.?
systemProp.http.proxyPort=8080
# Next line in form DOMAIN/USERNAME for NTLM or just USERNAME for non-NTLM
systemProp.http.proxyUser=DOMAIN/USERNAME
systemProp.http.proxyPassword=PASSWORD
systemProp.http.nonProxyHosts=localhost
# Next line is required for NTLM auth only
systemProp.http.auth.ntlm.domain=DOMAIN
systemProp.https.proxyHost=?.?.?.?
systemProp.https.proxyPort=8080
# Next line in form DOMAIN/USERNAME for NTLM or just USERNAME for non-NTLM
systemProp.https.proxyUser=DOMAIN/USERNAME
systemProp.https.proxyPassword=PASSWORD
systemProp.https.nonProxyHosts=localhost
# Next line is required for NTLM auth only
systemProp.https.auth.ntlm.domain=DOMAIN
Details of what gradle properties you can set are here... https://docs.gradle.org/current/userguide/userguide_single.html#sec%3aaccessing_the_web_via_a_proxy
For the selected value: $(this).val()
If you need the selected option element, $("option:selected", this)
Don't use device-width/height anymore.
device-width, device-height and device-aspect-ratio are deprecated in Media Queries Level 4: https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features
Just use width/height (without min/max) in combination with orientation & (min/max-)resolution to target specific devices. On mobile width/height should be the same as device-width/height.
There's not a way as of 11/2012, HOWEVER
Highlight Text (In visual Studio.net)
ctrl + k + c, ctrl + k + u
Will comment / uncomment, respectively
DECLARE @id_list VARCHAR(MAX) = '1234,23,56,576,1231,567,122,87876,57553,1216'
DECLARE @table TABLE ( id VARCHAR(50) )
DECLARE @x INT = 0
DECLARE @firstcomma INT = 0
DECLARE @nextcomma INT = 0
SET @x = LEN(@id_list) - LEN(REPLACE(@id_list, ',', '')) + 1 -- number of ids in id_list
WHILE @x > 0
BEGIN
SET @nextcomma = CASE WHEN CHARINDEX(',', @id_list, @firstcomma + 1) = 0
THEN LEN(@id_list) + 1
ELSE CHARINDEX(',', @id_list, @firstcomma + 1)
END
INSERT INTO @table
VALUES ( SUBSTRING(@id_list, @firstcomma + 1, (@nextcomma - @firstcomma) - 1) )
SET @firstcomma = CHARINDEX(',', @id_list, @firstcomma + 1)
SET @x = @x - 1
END
SELECT *
FROM @table
You need to use the OutputStreamWriter
class as the writer parameter for your BufferedWriter
. It does accept an encoding. Review javadocs for it.
Somewhat like this:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("jedis.txt"), "UTF-8"
));
Or you can set the current system encoding with the system property file.encoding
to UTF-8.
java -Dfile.encoding=UTF-8 com.jediacademy.Runner arg1 arg2 ...
You may also set it as a system property at runtime with System.setProperty(...)
if you only need it for this specific file, but in a case like this I think I would prefer the OutputStreamWriter
.
By setting the system property you can use FileWriter
and expect that it will use UTF-8 as the default encoding for your files. In this case for all the files that you read and write.
EDIT
Starting from API 19, you can replace the String "UTF-8" with StandardCharsets.UTF_8
As suggested in the comments below by tchrist, if you intend to detect encoding errors in your file you would be forced to use the OutputStreamWriter
approach and use the constructor that receives a charset encoder.
Somewhat like
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
encoder.onMalformedInput(CodingErrorAction.REPORT);
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("jedis.txt"),encoder));
You may choose between actions IGNORE | REPLACE | REPORT
Also, this question was already answered here.
You can set it to NULL
.
> Data$genome <- NULL
> head(Data)
chr region
1 chr1 CDS
2 chr1 exon
3 chr1 CDS
4 chr1 exon
5 chr1 CDS
6 chr1 exon
As pointed out in the comments, here are some other possibilities:
Data[2] <- NULL # Wojciech Sobala
Data[[2]] <- NULL # same as above
Data <- Data[,-2] # Ian Fellows
Data <- Data[-2] # same as above
You can remove multiple columns via:
Data[1:2] <- list(NULL) # Marek
Data[1:2] <- NULL # does not work!
Be careful with matrix-subsetting though, as you can end up with a vector:
Data <- Data[,-(2:3)] # vector
Data <- Data[,-(2:3),drop=FALSE] # still a data.frame
I recently came across this post and found some useful hints. However, I ended up using an entirely different approach which suited my needs. I am sharing the approach and my reasoning of why I chose this approach. The post is longer than I would have liked, but I believe screenshots are always helpful. Hopefully, the answer would be useful to someone.
My requirements were the following:
My Approach is as listed below:
To achieve requirements 2, 3 and 4 above, use table in Microsoft word, to insert the code snippet. Steps are listed below:
To achieve requirement 5, follow the steps below:
Please provide if you have any feedback or improvements or run into any issues with the approach.
I needed an easy-to-use C++ library for parsing CSV files but couldn't find any available, so I ended up building one. Rapidcsv is a C++11 header-only library which gives direct access to parsed columns (or rows) as vectors, in datatype of choice. For example:
#include <iostream>
#include <vector>
#include <rapidcsv.h>
int main()
{
rapidcsv::Document doc("../tests/msft.csv");
std::vector<float> close = doc.GetColumn<float>("Close");
std::cout << "Read " << close.size() << " values." << std::endl;
}
Here is a 100% working example for getting custom timezone Date Time in NodeJs without using any external modules:
const nDate = new Date().toLocaleString('en-US', {_x000D_
timeZone: 'Asia/Calcutta'_x000D_
});_x000D_
_x000D_
console.log(nDate);
_x000D_
Here are some real-world examples of the types of relationships:
A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.
To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).
For example:
CREATE TABLE Gov(
GID number(6) PRIMARY KEY,
Name varchar2(25),
Address varchar2(30),
TermBegin date,
TermEnd date
);
CREATE TABLE State(
SID number(3) PRIMARY KEY,
StateName varchar2(15),
Population number(10),
SGID Number(4) REFERENCES Gov(GID),
CONSTRAINT GOV_SDID UNIQUE (SGID)
);
INSERT INTO gov(GID, Name, Address, TermBegin)
values(110, 'Bob', '123 Any St', '1-Jan-2009');
INSERT INTO STATE values(111, 'Virginia', 2000000, 110);
A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.
To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).
For example:
CREATE TABLE Vendor(
VendorNumber number(4) PRIMARY KEY,
Name varchar2(20),
Address varchar2(20),
City varchar2(15),
Street varchar2(2),
ZipCode varchar2(10),
Contact varchar2(16),
PhoneNumber varchar2(12),
Status varchar2(8),
StampDate date
);
CREATE TABLE Inventory(
Item varchar2(6) PRIMARY KEY,
Description varchar2(30),
CurrentQuantity number(4) NOT NULL,
VendorNumber number(2) REFERENCES Vendor(VendorNumber),
ReorderQuantity number(3) NOT NULL
);
A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.
To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.
CREATE TABLE Class(
ClassID varchar2(10) PRIMARY KEY,
Title varchar2(30),
Instructor varchar2(30),
Day varchar2(15),
Time varchar2(10)
);
CREATE TABLE Student(
StudentID varchar2(15) PRIMARY KEY,
Name varchar2(35),
Major varchar2(35),
ClassYear varchar2(10),
Status varchar2(10)
);
CREATE TABLE ClassStudentRelation(
StudentID varchar2(15) NOT NULL,
ClassID varchar2(14) NOT NULL,
FOREIGN KEY (StudentID) REFERENCES Student(StudentID),
FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
UNIQUE (StudentID, ClassID)
);
String based operators will be deprecated in the future (You've probably seen the warning in console).
Getting this to work with symbolic operators was quite confusing for me, and I've updated the docs with two examples.
Post.findAll({
where: {
[Op.or]: [{authorId: 12}, {authorId: 13}]
}
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
Post.findAll({
where: {
authorId: {
[Op.or]: [12, 13]
}
}
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
I'm using Eclipse and defined MySql connection pool in META_INF/context.xml. Part of its content is:
<Context>
<Resource name="..."
driverClassName="com.mysql.jdbc.Driver"
... />
</Context>
When I changed the line starting with "driverClassName" as follows, problem is gone.
driverClassName="com.mysql.cj.jdbc.Driver"
If you want to redirect previous location or last request then you have to include user_agent
library:
$this->load->library('user_agent');
and then use at last in a function that you are using:
redirect($this->agent->referrer());
its working for me.
It has to do with the general workflow of Git. You're unlikely to be able to push directly to the main project's repository. I'm not sure if GitHub project's repository support branch-based access control, as you wouldn't want to grant anyone the permission to push to the master branch for example.
The general pattern is as follows:
Without this, it's quite unusual for public projects to let anyone push their own commits directly.