Here are the steps I went through in getting ffmpeg to work on Android:
make
away. You'll need to extract bionic(libc) and zlib(libz) from the Android build as well, as ffmpeg libraries depend on them.Create a dynamic library wrapping ffmpeg functionality using the Android NDK. There's a lot of documentation out there on how to work with the NDK. Basically you'll need to write some C/C++ code to export the functionality you need out of ffmpeg into a library java can interact with through JNI. The NDK allows you to easily link against the static libraries you've generated in step 1, just add a line similar to this to Android.mk: LOCAL_STATIC_LIBRARIES := libavcodec libavformat libavutil libc libz
Use the ffmpeg-wrapping dynamic library from your java sources. There's enough documentation on JNI out there, you should be fine.
Regarding using ffmpeg for playback, there are many examples (the ffmpeg binary itself is a good example), here's a basic tutorial. The best documentation can be found in the headers.
Good luck :)
I encountered this error since my encoded image started with data:image/png;base64,iVBORw0...
.
This answer led me to the solution:
String partSeparator = ",";
if (data.contains(partSeparator)) {
String encodedImg = data.split(partSeparator)[1];
byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
Files.write(destinationFile, decodedImg);
}
For SwiftUI, try
TextField ("Email", text: $email)
.textFieldStyle(RoundedBorderTextFieldStyle()).padding()
SecureField ("Password", text: $password)
.textFieldStyle(RoundedBorderTextFieldStyle()).padding()
You'll first need to separate your numpy array into two separate arrays containing x and y values.
x = [1, 2, 3, 9]
y = [1, 4, 1, 3]
curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like
def func(x, a, b):
return a*x + b
scipy.optimize.curve_fit(func, x, y)
will return a numpy array containing two arrays: the first will contain values for a
and b
that best fit your data, and the second will be the covariance of the optimal fit parameters.
Here's an example for a linear fit with the data you provided.
import numpy as np
from scipy.optimize import curve_fit
x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])
def fit_func(x, a, b):
return a*x + b
params = curve_fit(fit_func, x, y)
[a, b] = params[0]
This code will return a = 0.135483870968
and b = 1.74193548387
Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.
I had a similar problem but I came to a different solution that may help others. I used Spring Profiles to separate out test and app configuration classes.
Create a TestConfig class with a specific profile and exclude any app configuration from component scan you wish here.
In your test class set the profile to match the TestConfig and include it using the @ContextConfiguration annotation.
For example:
configuration:
@Profile("test")
@Configuration
@EnableWebMvc
@ComponentScan(
basePackages="your.base.package",
excludeFilters = {
@Filter(type = ASSIGNABLE_TYPE,
value = {
ExcludedAppConfig1.class,
ExcludedAppConfig2.class
})
})
public class TestConfig { ...}
test:
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
@WebAppConfiguration
public class SomeTest{ ... }
you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.
I actually had a very similar challenge on my current project. That broght me to the idea of writing a small script which I called docker-compose-profile (or short: dcp). I published this today on GitLab as docker-compose-profile.
So in short: I now can start several predefined docker-compose profiles using a command like dcp -p some-services "up -d"
. Feel free to try it out and give some feedback or suggestions for further improvements.
itoa was a non-standard helper function designed to complement the atoi standard function, and probably hiding a sprintf (Most its features can be implemented in terms of sprintf): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html
Use sprintf. Or snprintf. Or whatever tool you find.
Despite the fact some functions are not in the standard, as rightly mentioned by "onebyone" in one of his comments, most compiler will offer you an alternative (e.g. Visual C++ has its own _snprintf you can typedef to snprintf if you need it).
Use the C++ streams (in the current case std::stringstream (or even the deprecated std::strstream, as proposed by Herb Sutter in one of his books, because it's somewhat faster).
You're in C++, which means that you can choose the way you want it:
The faster way (i.e. the C way), but you should be sure the code is a bottleneck in your application (premature optimizations are evil, etc.) and that your code is safely encapsulated to avoid risking buffer overruns.
The safer way (i.e., the C++ way), if you know this part of the code is not critical, so better be sure this part of the code won't break at random moments because someone mistook a size or a pointer (which happens in real life, like... yesterday, on my computer, because someone thought it "cool" to use the faster way without really needing it).
If you want to use a the my_helper_method
inside a model, you can write:
ApplicationController.helpers.my_helper_method
Unfortunately:
It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.
It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.
What I want to accomplish: I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.
Here's the code I was hoping would complete this task:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1);
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);
for (int i = 0; i < 16; i++) {
if (prefs.getBoolean("itemKey[i]", true)) {
itemsArrayList.add(itemNames[i]);
}
}
What I did:
I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.
To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.
Here's the new code:
for (int i = 0; i < 16; i++) {
if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {
itemsArrayList.add(itemNames[i]);
}
}
Sorry to revive an old thread but should anyone be looking for an alternative solution where you store your string lists as one field in your database, here's how I solved that. Create a Converter like this:
import java.util.Arrays;
import java.util.List;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import static java.util.Collections.*;
@Converter
public class StringListConverter implements AttributeConverter<List<String>, String> {
private static final String SPLIT_CHAR = ";";
@Override
public String convertToDatabaseColumn(List<String> stringList) {
return stringList != null ? String.join(SPLIT_CHAR, stringList) : "";
}
@Override
public List<String> convertToEntityAttribute(String string) {
return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList();
}
}
Now use it on your Entities like this:
@Convert(converter = StringListConverter.class)
private List<String> yourList;
In the database, your list will be stored as foo;bar;foobar
, and in your Java object you will get a list with those strings.
Hope this is helpful to someone.
The basic difference is, like you stated, generating GUI events from the BackgroundWorker
. If the thread does not need to update the display or generate events for the main GUI thread, then it can be a simple thread.
Use the object tag:
<object data="http://iamawesome.com" type="text/html" width="200" height="200">
<a href="http://iamawesome.com">access the page directly</a>
</object>
Ref: http://debug.ga/embedding-external-pages-without-iframes/
For the first question, I find dev.print
to be the best when working interactively. First, you set up your plot visually and when you are happy with what you see, you can ask R to save the current plot to disk
dev.print(pdf, file="filename.pdf");
You can replace pdf
with other formats such as png
.
This will copy the image exactly as you see it on screen. The problem with dev.copy
is that the image is often different and doesn't remember the window size and aspect ratio - it forces the plot to be square by default.
For the second question, (as others have already answered), you must direct the output to disk before you execute your plotting commands
pdf('filename.pdf')
plot( yourdata )
points (some_more_data)
dev.off() # to complete the writing process and return output to your monitor
Use <>
to negate the where clause.
The following is works best in my opinion:
Get-Item Env:PATH
Get-ChildItem
. There's no hierarchy with environment variables.Set-Item -Path env:SomeVariable -Value "Some Value"
)Get-Item Env:
)I found the syntax odd at first, but things started making more sense after I understood the notion of Providers. Essentially PowerShell let's you navigate disparate components of the system in a way that's analogous to a file system.
What's the point of the trailing colon in Env:
? Try listing all of the "drives" available through Providers like this:
PS> Get-PSDrive
I only see a few results... (Alias, C, Cert, D, Env, Function, HKCU, HKLM, Variable, WSMan). It becomes obvious that Env
is simply another "drive" and the colon is a familiar syntax to anyone who's worked in Windows.
You can navigate the drives and pick out specific values:
Get-ChildItem C:\Windows
Get-Item C:
Get-Item Env:
Get-Item HKLM:
Get-ChildItem HKLM:SYSTEM
A cast, as Blaz Bratanic suggested:
size_t data = 99999999;
int convertdata = static_cast<int>(data);
is likely to silence the warning (though in principle a compiler can warn about anything it likes, even if there's a cast).
But it doesn't solve the problem that the warning was telling you about, namely that a conversion from size_t
to int
really could overflow.
If at all possible, design your program so you don't need to convert a size_t
value to int
. Just store it in a size_t
variable (as you've already done) and use that.
Converting to double
will not cause an overflow, but it could result in a loss of precision for a very large size_t
value. Again, it doesn't make a lot of sense to convert a size_t
to a double
; you're still better off keeping the value in a size_t
variable.
(R Sahu's answer has some suggestions if you can't avoid the cast, such as throwing an exception on overflow.)
A java.util.Date
is not a java.sql.Date
. It's the other way around. A java.sql.Date
is a java.util.Date
.
You'll need to convert it to a java.sql.Date
by using the constructor that takes a long
that a java.util.Date
can supply.
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
eof() checks the eofbit in the stream state.
On each read operation, if the position is at the end of stream and more data has to be read, eofbit is set to true. Therefore you're going to get an extra character before you get eofbit=1.
The correct way is to check whether the eof was reached (or, whether the read operation succeeded) after the reading operation. This is what your second version does - you do a read operation, and then use the resulting stream object reference (which >> returns) as a boolean value, which results in check for fail().
Add offset8
to your class, for example:
<div class="offset8">aligns to the right</div>
It is simply possible with childElementCount
in pure javascript
var countItems = document.getElementsByTagName("ul")[0].childElementCount;_x000D_
console.log(countItems);
_x000D_
<div id="selected">_x000D_
<ul>_x000D_
<li>29</li>_x000D_
<li>16</li>_x000D_
<li>5</li>_x000D_
<li>8</li>_x000D_
<li>10</li>_x000D_
<li>7</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Here is a working example in both Javascript and jQuery:
http://jsfiddle.net/GuLYN/312/
//In jQuery
$("#calculate").click(function() {
var num = parseFloat($("#textbox").val());
var new_num = $("#textbox").val(num.toFixed(2));
});
// In javascript
document.getElementById('calculate').onclick = function() {
var num = parseFloat(document.getElementById('textbox').value);
var new_num = num.toFixed(2);
document.getElementById('textbox').value = new_num;
};
?
numpy.random.seed(0)
numpy.random.randint(10, size=5)
This produces the following output:
array([5, 0, 3, 3, 7])
Again,if we run the same code we will get the same result.
Now if we change the seed value 0 to 1 or others:
numpy.random.seed(1)
numpy.random.randint(10, size=5)
This produces the following output: array([5 8 9 5 0])
but now the output not the same like above.
json-schema-generator is a neat Ruby based JSON schema generator. It supports both draft 3 and 4 of the JSON schema. It can be run as a standalone executable, or it can be embedded inside of a Ruby script.
Then you can use json-schema to validate JSON samples against your newly generated schema if you want.
Array.from()
takes an iterable object to convert to an array and an optional map function. You could create an object with a .length
property as follows:
return Array.from({length: this.props.level}, (item, index) =>
<span className="indent" key={index}></span>
);
Add the key "View Controller-based status bar appearance" from the dropdownlist as a row in info.plist
. Something like this:
You don't need to use any NPM modules to run a simple server, there's a very tiny library called "NPM Free Server" for Node:
50 lines of code, outputs if you are requesting a file or a folder and gives it a red or green color if it failed for worked. Less than 1KB in size (minified).
You can use a table
<table class="formcontrols" >
<tr>
<td>
<label for="firstName">FirstName:</label>
</td>
<td style="padding-left:10px;">
<input id="firstName" name="firstName" value="John">
</td>
</tr>
<tr>
<td>
<label for="Test">Last name:</label>
</td>
<td style="padding-left:10px;">
<input id="lastName" name="lastName" value="Travolta">
</td>
</tr>
</table>
The result would be: ImageResult
If you want for some reason to convert your file to base-64 string. Like if you want to pass it via internet, etc... you can do this
Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);
And correspondingly, read back to file:
Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
If you haven't found out yet, you can use the amazing screen plugin.
Conque is also exceptional but I find screen much more practical (it wont "litter" your buffer for example and you can just send the commands that you really want after editing them in your buffer)
Left Right Arrow with hover effect using Roko C. Buljan box-shadow trick
.arr {_x000D_
display: inline-block;_x000D_
padding: 1.2em;_x000D_
box-shadow: 8px 8px 0 2px #777 inset;_x000D_
}_x000D_
.arr.left {_x000D_
transform: rotate(-45deg);_x000D_
}_x000D_
.arr.right {_x000D_
transform: rotate(135deg);_x000D_
}_x000D_
.arr:hover {_x000D_
box-shadow: 8px 8px 0 2px #000 inset_x000D_
}
_x000D_
<div class="arr left"></div>_x000D_
<div class="arr right"></div>
_x000D_
The easiest way is this.
byte[] bytes = rs.getBytes("my_field");
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
I had H10
with Heroku and Node due to wrong name of the main code file. Edit package.json
:
{
...
"main": "correct_file_name.js",
...
"scripts": {
"start": "node correct_file_name.js"
}
}
Or rename the file.
From React type definition
type ReactInstance = Component<any, any> | Element;
....
refs: {
[key: string]: ReactInstance
};
So you can access you refs element as follow
stepInput = () => ReactDOM.findDOMNode(this.refs['stepInput']);
without redefinition of refs index.
As @manakor mentioned you can get error like
Property 'stepInput' does not exist on type '{ [key: string]: Component | Element; }
if you redefine refs(depends on IDE and ts version you use)
There is one more option now ( January-2015 )
Try this:
<?php
# Init the MySQL Connection
if( !( $db = mysql_connect( 'localhost' , 'root' , '' ) ) )
die( 'Failed to connect to MySQL Database Server - #'.mysql_errno().': '.mysql_error();
if( !mysql_select_db( 'ram' ) )
die( 'Connected to Server, but Failed to Connect to Database - #'.mysql_errno().': '.mysql_error();
# Prepare the INSERT Query
$insertTPL = 'INSERT INTO `name` VALUES( "%s" , "%s" , "%s" , "%s" )';
$insertSQL = sprintf( $insertTPL ,
mysql_real_escape_string( $name ) ,
mysql_real_escape_string( $add1 ) ,
mysql_real_escape_string( $add2 ) ,
mysql_real_escape_string( $mail ) );
# Execute the INSERT Query
if( !( $insertRes = mysql_query( $insertSQL ) ) ){
echo '<p>Insert of Row into Database Failed - #'.mysql_errno().': '.mysql_error().'</p>';
}else{
echo '<p>Person\'s Information Inserted</p>'
}
# Prepare the SELECT Query
$selectSQL = 'SELECT * FROM `names`';
# Execute the SELECT Query
if( !( $selectRes = mysql_query( $selectSQL ) ) ){
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}else{
?>
<table border="2">
<thead>
<tr>
<th>Name</th>
<th>Address Line 1</th>
<th>Address Line 2</th>
<th>Email Id</th>
</tr>
</thead>
<tbody>
<?php
if( mysql_num_rows( $selectRes )==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysql_fetch_assoc( $selectRes ) ){
echo "<tr><td>{$row['name']}</td><td>{$row['addr1']}</td><td>{$row['addr2']}</td><td>{$row['mail']}</td></tr>\n";
}
}
?>
</tbody>
</table>
<?php
}
?>
Your initial solution did not show any obvious santisation of the values before passing them into the Database. This is how SQL Injection attacks (or even un-intentional errors being passed through SQL) occur. Don't do it!
Your database does not seem to have a Primary Key. Whilst these are not, technically, necessary in all usage, they are a good practice, and make for a much more reliable way of referring to a specific row in a table, whether for adding related tables, or for making changes within that table.
You need to check every action, at every stage, for errors. Most PHP functions are nice enough to have a response they will return under an error condition. It is your job to check for those conditions as you go - never assume that PHP will do what you expect, how you expect, and in the order you expect. This is how accident happen...
My provided code above contains alot of points where, if an error has occured, a message will be returned. Try it, see if any error messages are reported, look at the Error Message, and, if applicable, the Error Code returned and do some research.
Good luck.
Here a complete example :
Suppose we have a Person class like :
public class Person
{
protected String fname;
protected String lname;
public Person()
{
}
public Person(String fname, String lname)
{
this.fname = fname;
this.lname = lname;
}
public boolean equals(Object objet)
{
if(objet instanceof Person)
{
Person p = (Person) objet;
return (p.getFname().equals(this.fname)) && p.getLname().equals(this.lname));
}
else return super.equals(objet);
}
@Override
public String toString()
{
return "Person(fname : " + getFname + ", lname : " + getLname + ")";
}
/** Getters and Setters **/
}
Now we create a comparator :
import java.util.Comparator;
public class ComparePerson implements Comparator<Person>
{
@Override
public int compare(Person p1, Person p2)
{
if(p1.getFname().equalsIgnoreCase(p2.getFname()))
{
return p1.getLname().compareTo(p2.getLname());
}
return p1.getFname().compareTo(p2.getFname());
}
}
Finally suppose we have a group of persons :
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Group
{
protected List<Person> listPersons;
public Group()
{
this.listPersons = new ArrayList<Person>();
}
public Group(List<Person> listPersons)
{
this.listPersons = listPersons;
}
public void order(boolean asc)
{
Comparator<Person> comp = asc ? new ComparePerson() : Collections.reverseOrder(new ComparePerson());
Collections.sort(this.listPersons, comp);
}
public void display()
{
for(Person p : this.listPersons)
{
System.out.println(p);
}
}
/** Getters and Setters **/
}
Now we try this :
import java.util.ArrayList;
import java.util.List;
public class App
{
public static void main(String[] args)
{
Group g = new Group();
List listPersons = new ArrayList<Person>();
g.setListPersons(listPersons);
Person p;
p = new Person("A", "B");
listPersons.add(p);
p = new Person("C", "D");
listPersons.add(p);
/** you can add Person as many as you want **/
g.display();
g.order(true);
g.display();
g.order(false);
g.display();
}
}
You probably can't. Here's something that comes close. You won't get content to flow around it if there's space below.
http://jsfiddle.net/ThnLk/1289
.stuck {
position: fixed;
top: 10px;
left: 10px;
bottom: 10px;
width: 180px;
overflow-y: scroll;
}
You can do a percentage height as well:
http://jsfiddle.net/ThnLk/1287/
.stuck {
max-height: 100%;
}
Just:
$('#edit-submitted-first-name').removeAttr('required');?????
If you're interested in further reading take a look here.
EXPLAIN PLAN FOR
In SQL Developer, you don't have to use EXPLAIN PLAN FOR
statement. Press F10
or click the Explain Plan icon.
It will be then displayed in the Explain Plan window.
If you are using SQL*Plus then use DBMS_XPLAN.
For example,
SQL> EXPLAIN PLAN FOR
2 SELECT * FROM DUAL;
Explained.
SQL> SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------
Plan hash value: 272002086
--------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 2 | 2 (0)| 00:00:01 |
| 1 | TABLE ACCESS FULL| DUAL | 1 | 2 | 2 (0)| 00:00:01 |
--------------------------------------------------------------------------
8 rows selected.
SQL>
Just use = IF(A1="Bla*","YES","NO")
. When you insert the asterisk, it acts as a wild card for any amount of characters after the specified text.
For random hash values, some engineers said golden ratio prime number(2654435761) is a bad choice, with my testing results, I found that it's not true; instead, 2654435761 distributes the hash values pretty good.
#define MCR_HashTableSize 2^10
unsigned int
Hash_UInt_GRPrimeNumber(unsigned int key)
{
key = key*2654435761 & (MCR_HashTableSize - 1)
return key;
}
The hash table size must be a power of two.
I have written a test program to evaluate many hash functions for integers, the results show that GRPrimeNumber is a pretty good choice.
I have tried:
With my testing results, I found that Golden Ratio Prime Number always has the fewer empty buckets or zero empty bucket and the shortest collision chain length.
Some hash functions for integers are claimed to be good, but the testing results show that when the total_data_entry / total_bucket_number = 3, the longest chain length is bigger than 10(max collision number > 10), and many buckets are not mapped(empty buckets), which is very bad, compared with the result of zero empty bucket and longest chain length 3 by Golden Ratio Prime Number Hashing.
BTW, with my testing results, I found one version of shifting-xor hash functions is pretty good(It's shared by mikera).
unsigned int Hash_UInt_M3(unsigned int key)
{
key ^= (key << 13);
key ^= (key >> 17);
key ^= (key << 5);
return key;
}
Here is a locale independent solution (copy to a file named SetDateTimeComponents.cmd):
@echo off
REM This script taken from the following URL:
REM http://www.winnetmag.com/windowsscripting/article/articleid/9177/windowsscripting_9177.html
REM Create the date and time elements.
for /f "tokens=1-7 delims=:/-, " %%i in ('echo exit^|cmd /q /k"prompt $d $t"') do (
for /f "tokens=2-4 delims=/-,() skip=1" %%a in ('echo.^|date') do (
set dow=%%i
set %%a=%%j
set %%b=%%k
set %%c=%%l
set hh=%%m
set min=%%n
set ss=%%o
)
)
REM Let's see the result.
echo %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss%
I put all my .cmd scripts into the same folder (%SCRIPTROOT%); any script that needs date/time values will call SetDateTimeComponents.cmd as in the following example:
setlocal
@echo Initializing...
set SCRIPTROOT=%~dp0
set ERRLOG=C:\Oopsies.err
:: Log start time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
@echo === %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss% : Start === >> %ERRLOG%
:: Perform some long running action and log errors to ERRLOG.
:: Log end time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
@echo === %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss% : End === >> %ERRLOG%
As the example shows, you can call SetDateTimeComponents.cmd whenever you need to update the date/time values. Hiding the time parsing script in it's own SetDateTimeComponents.cmd file is a nice way to hide the ugly details, and, more importantly, avoid typos.
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress();
Also, add below permission in your manifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Please refer to Android 6.0 Changes.
To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.
To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.
Here are a few options for changing text / label sizes
library(ggplot2)
# Example data using mtcars
a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=20)
The size
in the geom_text
changes the size of the geom_text
labels.
p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels
p <- p + theme(axis.title = element_text(size = 25)) # change axis titles
p <- p + theme(text = element_text(size = 10)) # this will change all text size
# (except geom_text)
For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?
Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text
sizes to theme
sizes.
So a horrible fix for uniform sizes is to scale by this ratio
geom.text.size = 7
theme.size = (14/5) * geom.text.size
ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=geom.text.size) +
theme(axis.text = element_text(size = theme.size, colour="black"))
This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)
A other users suggested,
.empty()
is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.
If you wish to keep data, like event handlers for example, you should use
.detach()
as described on the JQuery's API detach documentation.
The method .remove() could be usefull for similar purposes.
You can use Collections.list()
to convert an Enumeration
to a List
in one line:
List<T> list = Collections.list(enumeration);
There's no similar method to get a Set
, however you can still do it one line:
Set<T> set = new HashSet<T>(Collections.list(enumeration));
The OS failed to install the required update Windows8.1-KB2999226-x64.msu. However I tried to find the particular update from -
C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu.
I couldn't find it there so I installed the kb2999226 update from here (Windows 10 Universal C runtime)
Then I installed the update according to my OS and after that It was working fine.
If there is not substantial history on one end (aka if it is just a single readme commit on the github end), I often find it easier to manually copy the readme to my local repo and do a git push -f
to make my version the new root commit.
I find it is slightly less complicated, doesn't require remembering an obscure flag, and keeps the history a bit cleaner.
yes, thats possible. just use the rgba-syntax for your background-color.
.menue{
background-color: rgba(255, 0, 0, 0.5); //semi-transparent red
}
I had to look for them in C:\Users\Dell\AppData\Local\Arduino15\
I had to take help from the "date created" and "date modified" attributes to identify which libraries to delete.
But the names still show in the IDE... But it is something I can live with for now.
.NET and .NET Core are two different implementations of the .NET runtime. Both Core and Framework (but especially Framework) have different profiles that include larger or smaller (or just plain different) selections of the many APIs and assemblies Microsoft has created for .NET, depending on where they are installed and in what profile.
For example, there are some different APIs available in Universal Windows apps than in the "normal" Windows profile. Even on Windows, you might have the "Client" profile vs. the "Full" profile. Additionally, and there are other implementations (like Mono) that have their own sets of libraries.
.NET Standard is a specification for which sets of API libraries and assemblies must be available. An app written for .NET Standard 1.0 should be able to compile and run with any version of Framework, Core, Mono, etc., that advertises support for the .NET Standard 1.0 collection of libraries. Similar is true for .NET Standard 1.1, 1.5, 1.6, 2.0, etc. As long as the runtime provides support for the version of Standard targeted by your program, your program should run there.
A project targeted at a version of Standard will not be able to make use of features that are not included in that revision of the standard. This doesn't mean you can't take dependencies on other assemblies, or APIs published by other vendors (i.e.: items on NuGet). But it does mean that any dependencies you take must also include support for your version of .NET Standard. .NET Standard is evolving quickly, but it's still new enough, and cares enough about some of the smaller runtime profiles, that this limitation can feel stifling. (Note a year and a half later: this is starting to change, and recent .NET Standard versions are much nicer and more full-featured).
On the other hand, an app targeted at Standard should be able to be used in more deployment situations, since in theory it can run with Core, Framework, Mono, etc. For a class library project looking for wide distribution, that's an attractive promise. For a class library project used mainly for internal purposes, it may not be as much of a concern.
.NET Standard can also be useful in situations where the system administrator team is wanting to move from ASP.NET on Windows to ASP.NET for .NET Core on Linux for philosophical or cost reasons, but the Development team wants to continue working against .NET Framework in Visual Studio on Windows.
There is no built-in method that allows what you intend to do.
You have to add a method to your repository, like this:
public function getWhatYouWant()
{
$qb = $this->createQueryBuilder('u');
$qb->where('u.id != :identifier')
->setParameter('identifier', 1);
return $qb->getQuery()
->getResult();
}
Hope this helps.
If you would like to have live reload you can use gulp-webserver, which will watch for your file changes and reload page, this way you don't have to press F5 every time on your page:
Here is how to do it:
Open command prompt (cmd) and type
npm install --save-dev gulp-webserver
Enter Ctrl+Shift+P in VS Code and type Configure Task Runner. Select it and press enter. It will open tasks.json file for you. Remove everything from it end enter just following code
tasks.json
{
"version": "0.1.0",
"command": "gulp",
"isShellCommand": true,
"args": [
"--no-color"
],
"tasks": [
{
"taskName": "webserver",
"isBuildCommand": true,
"showOutput": "always"
}
]
}
gulpfile.js
var gulp = require('gulp'),
webserver = require('gulp-webserver');
gulp.task('webserver', function () {
gulp.src('app')
.pipe(webserver({
livereload: true,
open: true
}));
});
Your webserver now will open your page in your default browser. Now any changes that you will do to your HTML or CSS pages will be automatically reloaded.
Here is an information on how to configure 'gulp-webserver' for instance port, and what page to load, ...
You can also run your task just by entering Ctrl+P and type task webserver
[System.IO.Directory]::CreateDirectory('full path to directory')
This internally checks for directory existence, and creates one, if there is no directory. Just one line and native .NET method working perfectly.
In python3.6+
you can use the secrets
module:
The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.
In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.
In testing generation of 768bit
security tokens I found:
random.choices()
- 0.000246
secssecrets.choice()
- 0.003529
secsThe secrets
modules is slower but outside of testing it is what you should be using for cryptographic purposes:
import string, secrets
def random_string(size):
letters = string.ascii_lowercase+string.ascii_uppercase+string.digits
return ''.join(secrets.choice(letters) for i in range(size))
print(random_string(768))
Depending on the language you're using it's going to be something simple like
CInt(CDate("1970-1-1") - CDate(Today()))
Ironically enough, yesterday was day 40,000 if you use 1/1/1900 as "day zero" like many computer systems use.
Seen a lot of recommendations to use a ConcurrentDictionary
, but no solid examples of it, so I'm going to throw my hat into this solution race. I'm not a thread-safe developer, so if this code isn't solid, please speak up for the sake of those who follow after.
public static class XmlSerializerHelper
{
private static readonly ConcurrentDictionary<Type, XmlSerializer> TypeSerializers = new ConcurrentDictionary<Type, XmlSerializer>();
public static XmlSerializer GetSerializer(Type type)
{
return TypeSerializers.GetOrAdd(type,
t =>
{
var importer = new XmlReflectionImporter();
var mapping = importer.ImportTypeMapping(t, null, null);
return new XmlSerializer(mapping);
});
}
}
I've seen other posts involving ConcurrentDictionary
and Lazy
loading the value. I'm not sure if that's relevant here or not, but here's the code for that:
private static readonly ConcurrentDictionary<Type, Lazy<XmlSerializer>> TypeSerializers = new ConcurrentDictionary<Type, Lazy<XmlSerializer>>();
public static XmlSerializer GetSerializer(Type type)
{
return TypeSerializers.GetOrAdd(type,
t =>
{
var importer = new XmlReflectionImporter();
var mapping = importer.ImportTypeMapping(t, null, null);
var lazyResult = new Lazy<XmlSerializer>(() => new XmlSerializer(mapping), LazyThreadSafetyMode.ExecutionAndPublication);
return lazyResult;
}).Value;
}
Throwing this in for PowerShell 2.0 and upwards:
Run New-EventLog
once to register the event source:
New-EventLog -LogName Application -Source MyApp
Then use Write-EventLog
to write to the log:
Write-EventLog
-LogName Application
-Source MyApp
-EntryType Error
-Message "Immunity to iocaine powder not detected, dying now"
-EventId 1
Both options are already mentioned in the existing answers:
from django.db.models import Q
q1 = User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))
and
q2 = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
However, there seems to be some confusion regarding which one is to prefer.
The point is that they are identical on the SQL level, so feel free to pick whichever you like!
The Django ORM Cookbook talks in some detail about this, here is the relevant part:
queryset = User.objects.filter(
first_name__startswith='R'
) | User.objects.filter(
last_name__startswith='D'
)
leads to
In [5]: str(queryset.query)
Out[5]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'
and
qs = User.objects.filter(Q(first_name__startswith='R') | Q(last_name__startswith='D'))
leads to
In [9]: str(qs.query)
Out[9]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'
source: django-orm-cookbook
ES6 setTimeout
setTimeout(() => {
console.log("we waited 204586560000 ms to run this code, oh boy wowwoowee!");
}, 204586560000);
Edit: 204586560000 ms is the approximate time between the original question and this answer... assuming I calculated correctly.
It seems that the original test case is wrong.
I can confirm that the selector #my_parent_element *
works with unbind()
.
Let's take the following html as an example:
<div id="#my_parent_element">
<div class="div1">
<div class="div2">hello</div>
<div class="div3">my</div>
</div>
<div class="div4">name</div>
<div class="div5">
<div class="div6">is</div>
<div class="div7">
<div class="div8">marco</div>
<div class="div9">(try and click on any word)!</div>
</div>
</div>
</div>
<button class="unbind">Now, click me and try again</button>
And the jquery bit:
$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
alert('hi!');
})
$('button.unbind').click(function() {
$('#my_parent_element *').unbind('click');
})
You can try it here: http://jsfiddle.net/fLvwbazk/7/
For substracting in moment.js:
moment().subtract(1, 'months').format('MMM YYYY');
Documentation:
http://momentjs.com/docs/#/manipulating/subtract/
Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).
moment().subtract('seconds', 1); // Deprecated in 2.8.0
moment().subtract(1, 'seconds');
As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.
moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
Connect didn't work for me, The problem was that Genymotion uses its own dk-tools and you need to change it to custom SDK tools.
More info: https://stackoverflow.com/a/26630862/4154438
You get an ExceptionInInitializerError if something goes wrong in the static initializer block.
class C
{
static
{
// if something does wrong -> ExceptionInInitializerError
}
}
Because static variables are initialized in static blocks there are a source of these errors too. An example:
class C
{
static int v = D.foo();
}
=>
class C
{
static int v;
static
{
v = D.foo();
}
}
So if foo() goes wild, you get a ExceptionInInitializerError.
Use git reset --soft HEAD~
in the cmd from the .sln folder
I was facing it today and was overwhelmed that VSCode
suggests such thing, whereas it's big brother Visual Studio
doesn't.
Most of the answers were helpful; if I have more commits that were made before, losing them all would be frustrating.
Moreover, if VSCode
does it in half a second, it shouldn't be complex.
Only jessehouwing's answer was the closest to a simple solution.
Go to Team Explorer
-> Sync
.
There you'd see the all the commits. Press the Actions
dropdown and Open Command Prompt
You'll have the cmd window prompted, there write git reset --soft HEAD~
.
If there are multiple undesired commits, add the amount after the ~
(i.e git reset --soft HEAD~5
)
(If you're not using git
, check colloquial usage).
I hope it will help, and hopefully in the next version VS team will add it builtin
First of all, they both are the non-scalar objects (also known as a compound objects) in Python.
+
(brand new tuple will be created of course)(3,) # -> (3)
instead of (3) # -> 3
[3]
new_array = origin_array[:]
[x**2 for x in range(1,7)]
gives you
[1,4,9,16,25,36]
(Not readable)Using list may also cause an aliasing bug (two distinct paths pointing to the same object).
{
"files.useExperimentalFileWatcher" : true
}
in Code -> Preferences -> Settings
Tested with Visual Studio Code Version 1.26.1 on mac and win
You can also try using the one-jar maven plugin which fixed the problem for us. Simply follow the instructions from here.
Swift 4.2
write this in viewDidLoad
// to detect if TextField changed
TextField.addTarget(self, action: #selector(textFieldDidChange(_:)),
for: UIControl.Event.editingChanged)
write this outside viewDidLoad
@objc func textFieldDidChange(_ textField: UITextField) {
// do something
}
You could change the event by UIControl.Event.editingDidBegin or what ever you want to detect.
It is WiFi bug due to wifi disable or not properly connected.
Simply Reconnect the wifi will solve the issue.
There is another answer here that also fits the authors request: 'compile-time' way to get all property names defined interface
If you use the plugin ts-transformer-keys and an Interface to your class you can get all the keys for the class.
But if you're using Angular or React then in some scenarios there is additional configuration necessary (webpack and typescript) to get it working: https://github.com/kimamula/ts-transformer-keys/issues/4
If you're only looking for one:
import re
match = re.search(r'href=[\'"]?([^\'" >]+)', s)
if match:
print(match.group(1))
If you have a long string, and want every instance of the pattern in it:
import re
urls = re.findall(r'href=[\'"]?([^\'" >]+)', s)
print(', '.join(urls))
Where s
is the string that you're looking for matches in.
Quick explanation of the regexp bits:
r'...'
is a "raw" string. It stops you having to worry about escaping characters quite as much as you normally would. (\
especially -- in a raw string a\
is just a\
. In a regular string you'd have to do\\
every time, and that gets old in regexps.)"
href=[\'"]?
" says to match "href=", possibly followed by a'
or"
. "Possibly" because it's hard to say how horrible the HTML you're looking at is, and the quotes aren't strictly required.Enclosing the next bit in "
()
" says to make it a "group", which means to split it out and return it separately to us. It's just a way to say "this is the part of the pattern I'm interested in.""
[^\'" >]+
" says to match any characters that aren't'
,"
,>
, or a space. Essentially this is a list of characters that are an end to the URL. It lets us avoid trying to write a regexp that reliably matches a full URL, which can be a bit complicated.
The suggestion in another answer to use BeautifulSoup isn't bad, but it does introduce a higher level of external requirements. Plus it doesn't help you in your stated goal of learning regexps, which I'd assume this specific html-parsing project is just a part of.
It's pretty easy to do:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_to_parse)
for tag in soup.findAll('a', href=True):
print(tag['href'])
Once you've installed BeautifulSoup, anyway.
From the command line it would be just:
svn update
(in the directory you've got a copy of a SVN project).
If you are using Carbon (and you should, it's awesome!) with Laravel, you can simply do the following:
->where('created_at', '>=', Carbon::today())
Besides now()
and today()
, you can also use yesterday()
and tomorrow()
and then use the following:
startOfDay()
/endOfDay()
startOfWeek()
/endOfWeek()
startOfMonth()
/endOfMonth()
startOfYear()
/endOfYear()
startOfDecade()
/endOfDecade()
startOfCentury()
/endOfCentury()
Using is_numeric()
for checking if a variable is an integer is a bad idea. This function will return TRUE
for 3.14
for example. It's not the expected behavior.
To do this correctly, you can use one of these options:
Considering this variables array :
$variables = [
"TEST 0" => 0,
"TEST 1" => 42,
"TEST 2" => 4.2,
"TEST 3" => .42,
"TEST 4" => 42.,
"TEST 5" => "42",
"TEST 6" => "a42",
"TEST 7" => "42a",
"TEST 8" => 0x24,
"TEST 9" => 1337e0
];
# Check if your variable is an integer
if ( filter_var($variable, FILTER_VALIDATE_INT) === false ) {
echo "Your variable is not an integer";
}
Output :
TEST 0 : 0 (type:integer) is an integer ?
TEST 1 : 42 (type:integer) is an integer ?
TEST 2 : 4.2 (type:double) is not an integer ?
TEST 3 : 0.42 (type:double) is not an integer ?
TEST 4 : 42 (type:double) is an integer ?
TEST 5 : 42 (type:string) is an integer ?
TEST 6 : a42 (type:string) is not an integer ?
TEST 7 : 42a (type:string) is not an integer ?
TEST 8 : 36 (type:integer) is an integer ?
TEST 9 : 1337 (type:double) is an integer ?
# Check if your variable is an integer
if ( strval($variable) !== strval(intval($variable)) ) {
echo "Your variable is not an integer";
}
Output :
TEST 0 : 0 (type:integer) is an integer ?
TEST 1 : 42 (type:integer) is an integer ?
TEST 2 : 4.2 (type:double) is not an integer ?
TEST 3 : 0.42 (type:double) is not an integer ?
TEST 4 : 42 (type:double) is an integer ?
TEST 5 : 42 (type:string) is an integer ?
TEST 6 : a42 (type:string) is not an integer ?
TEST 7 : 42a (type:string) is not an integer ?
TEST 8 : 36 (type:integer) is an integer ?
TEST 9 : 1337 (type:double) is an integer ?
# Check if your variable is an integer
if ( ! ctype_digit(strval($variable)) ) {
echo "Your variable is not an integer";
}
Output :
TEST 0 : 0 (type:integer) is an integer ?
TEST 1 : 42 (type:integer) is an integer ?
TEST 2 : 4.2 (type:double) is not an integer ?
TEST 3 : 0.42 (type:double) is not an integer ?
TEST 4 : 42 (type:double) is an integer ?
TEST 5 : 42 (type:string) is an integer ?
TEST 6 : a42 (type:string) is not an integer ?
TEST 7 : 42a (type:string) is not an integer ?
TEST 8 : 36 (type:integer) is an integer ?
TEST 9 : 1337 (type:double) is an integer ?
# Check if your variable is an integer
if ( ! preg_match('/^\d+$/', $variable) ) {
echo "Your variable is not an integer";
}
Output :
TEST 0 : 0 (type:integer) is an integer ?
TEST 1 : 42 (type:integer) is an integer ?
TEST 2 : 4.2 (type:double) is not an integer ?
TEST 3 : 0.42 (type:double) is not an integer ?
TEST 4 : 42 (type:double) is an integer ?
TEST 5 : 42 (type:string) is an integer ?
TEST 6 : a42 (type:string) is not an integer ?
TEST 7 : 42a (type:string) is not an integer ?
TEST 8 : 36 (type:integer) is an integer ?
TEST 9 : 1337 (type:double) is an integer ?
A very easy solution to this problem is to do this.
<ul>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php">Home</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'portfolio.php'){echo 'current'; }else { echo ''; } ?>"><a href="portfolio.php">Portfolio</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'services.php'){echo 'current'; }else { echo ''; } ?>"><a href="services.php">Services</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'contact.php'){echo 'current'; }else { echo ''; } ?>"><a href="contact.php">Contact</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'links.php'){echo 'current'; }else { echo ''; } ?>"><a href="links.php">Links</a></li>
</ul>
Which will output
<ul>
<li class="current"><a href="index.php">Home</a></li>
<li class=""><a href="portfolio.php">Portfolio</a></li>
<li class=""><a href="services.php">Services</a></li>
<li class=""><a href="contact.php">Contact</a></li>
<li class=""><a href="links.php">Links</a></li>
</ul>
There may not be anything 'Python specific', but the KDE and GNOME desktops offer text-to-speech as a part of their accessibility support, and also offer python library bindings. It may be possible to use the python bindings to control the desktop libraries for text to speech.
If using the Jython implementation of Python on the JVM, the FreeTTS system may be usable.
Finally, OSX and Windows have native APIs for text to speech. It may be possible to use these from python via ctypes or other mechanisms such as COM.
Let's use some java 8 feature:
IntStream.iterate(10, x -> x + 10).limit(5)
.forEach(System.out::println);
If you need to store the numbers you can collect them into a collection eg:
List numbers = IntStream.iterate(10, x -> x + 10).limit(5)
.boxed()
.collect(Collectors.toList());
And some delay added:
IntStream.iterate(10, x -> x + 10).limit(5)
.forEach(x -> {
System.out.println(x);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// Do something with the exception
}
});
Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.
There is no need for capture groups. Just match id=
then forget those characters with \K
, then isolate the following one or more digital characters.
Code (Demo)
$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';
Output:
736375493
In IIS >= 7, a <webLimits>
section has replaced ConnectionTimeout
, HeaderWaitTimeout
, MaxGlobalBandwidth
, and MinFileBytesPerSec
IIS 6 metabase settings.
Example Configuration:
<configuration>
<system.applicationHost>
<webLimits connectionTimeout="00:01:00"
dynamicIdleThreshold="150"
headerWaitTimeout="00:00:30"
minBytesPerSecond="500"
/>
</system.applicationHost>
</configuration>
For reference: more information regarding these settings in IIS can be found here. Also, I was unable to add this section to the web.config via the IIS manager's "configuration editor", though it did show up once I added it and searched the configuration.
I gathered insights from a bunch of answers here and I present a comprehensive solution:
So, if you setup nginx with php5-fpm and log a message using error_log()
you can see it in /var/log/nginx/error.log
by default.
A problem can arise if you want to log a lot of data (say an array) using error_log(print_r($myArr, true));
. If an array is large enough, it seems that nginx
will truncate your log entry.
To get around this you can configure fpm
(php.net fpm config) to manage logs. Here are the steps to do so.
Open /etc/php5/fpm/pool.d/www.conf
:
$ sudo nano /etc/php5/fpm/pool.d/www.conf
Uncomment the following two lines by removing ;
at the beginning of the line: (error_log is defined here: php.net)
;php_admin_value[error_log] = /var/log/fpm-php.www.log
;php_admin_flag[log_errors] = on
Create /var/log/fpm-php.www.log
:
$ sudo touch /var/log/fpm-php.www.log;
Change ownership of /var/log/fpm-php.www.log
so that php5-fpm can edit it:
$ sudo chown vagrant /var/log/fpm-php.www.log
Note: vagrant
is the user that I need to give ownership to. You can see what user this should be for you by running $ ps aux | grep php.*www
and looking at first column.
Restart php5-fpm:
$ sudo service php5-fpm restart
Now your logs will be in /var/log/fpm-php.www.log
.
From here.
“Slug” is a newspaper term, but what it means here is the final bit of the URL. For example, a post with the title, “A bit about Django” would become, “bit-about-django” automatically (you can, of course, change it easily if you don’t like the auto-generated slug).
selecting
with the the help of the mouse
and right-click copy
worked in my case.
I didn't want the line numbers included so I :set nonumber
before copying
.
Using Google Guava:
CharMatcher.inRange('0','9').retainFrom("123-456-789")
UPDATE:
Using Precomputed CharMatcher can further improve performance
CharMatcher ASCII_DIGITS=CharMatcher.inRange('0','9').precomputed();
ASCII_DIGITS.retainFrom("123-456-789");
I know that this question has been answered, And all the answers are nice. But I wanted to add my two cents to this question for people who have similar (but not exactly the same) problem.
In a more general way, we can do something like this:
$('body').click(function(evt){
if(!$(evt.target).is('#menu_content')) {
//event handling code
}
});
This way we can handle not only events fired by anything except element with id menu_content
but also events that are fired by anything except any element that we can select using CSS selectors.
For instance in the following code snippet I am getting events fired by any element except all <li>
elements which are descendants of div element with id myNavbar
.
$('body').click(function(evt){
if(!$(evt.target).is('div#myNavbar li')) {
//event handling code
}
});
You can use a transformation for your data frame:
df = pd.DataFrame(my_data condition)
df = df*1
If you are using Git Gui on windows,
please check the below code for more details
package FirstTestNgPackage;
import java.util.ArrayList;
import java.util.Arrays;
public class testingclass {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.out.println("Hello");
int size = 7;
String myArray[] = new String[size];
System.out.println("Enter elements of the array (Strings) :: ");
for(int i=0; i<size; i++)
{
myArray[i] = "testing"+i;
}
System.out.println(Arrays.toString(myArray));
ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));
System.out.println("Enter the element that is to be added:");
myArray = myList.toArray(myArray);
someFunction(myArray);
}
public static void someFunction(String[] strArray)
{
System.out.println("in function");
System.out.println("in function length"+strArray.length );
System.out.println(Arrays.toString(strArray));
}
}
just copy it and past... your code.. it will work.. and then you understand how to pass string array as a parameter ...
Thank you
Personally I don't find the standard diagramming technique very helpful - the arrows always seem to point the wrong way for me. (They generally point towards the "parent" of each commit, which ends up being backwards in time, which is weird).
To explain it in words:
For reasons I don't understand, GUI tools for Git have never made much of an effort to present merge histories more cleanly, abstracting out the individual merges. So if you want a "clean history", you need to use rebase.
I seem to recall having read blog posts from programmers who only use rebase and others that never use rebase.
I'll try explaining this with a just-words example. Let's say other people on your project are working on the user interface, and you're writing documentation. Without rebase, your history might look something like:
Write tutorial
Merge remote-tracking branch 'origin/master' into fixdocs
Bigger buttons
Drop down list
Extend README
Merge remote-tracking branch 'origin/master' into fixdocs
Make window larger
Fix a mistake in howto.md
That is, merges and UI commits in the middle of your documentation commits.
If you rebased your code onto master instead of merging it, it would look like this:
Write tutorial
Extend README
Fix a mistake in howto.md
Bigger buttons
Drop down list
Make window larger
All of your commits are at the top (newest), followed by the rest of the master
branch.
(Disclaimer: I'm the author of the "10 things I hate about Git" post referred to in another answer)
Here's a simple way to do it without RegEx.
You can prototype and/or cache things as desired.
// Example: translate( 'faded', 'abcdef', '123456' ) returns '61454'
function translate( s, sFrom, sTo ){
for ( var out = '', i = 0; i < s.length; i++ ){
out += sTo.charAt( sFrom.indexOf( s.charAt(i) ));
}
return out;
}
this is how I implement it .
let dictionary = self.convertStringToDictionary(responceString)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SOCKET_UPDATE"), object: dictionary)
Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. (MSDN, SqlConnection.ConnectionTimeout Property, 2013)
You may use clone()
which works well if your object has immutable objects and/or primitives, but it may be a little problematic when you don't have these ( such as collections ) for which you may need to perform a deep clone.
User userCopy = (User) user.clone();//make a copy
for(...) {
user.age = 1;
user.id = -1;
UserDao.update(user)
user = userCopy;
}
It seems like you just want to preserve the attributes: age
and id
which are of type int
so, why don't you give it a try and see if it works.
For more complex scenarios you could create a "copy" method:
publc class User {
public static User copy( User other ) {
User newUser = new User();
newUser.age = other.age;
newUser.id = other.id;
//... etc.
return newUser;
}
}
It should take you about 10 minutes.
And then you can use that instead:
User userCopy = User.copy( user ); //make a copy
// etc.
To read more about clone read this chapter in Joshua Bloch "Effective Java: Override clone judiciously"
methods for setting attributes(for example class) on an element: 1. el.className = string 2. el.setAttribute('class',string) 3. el.attributes.setNamedItem(object) 4. el.setAttributeNode(node)
I have made a simple benchmark test (here)
and it seems that setAttributeNode is about 3 times faster then using setAttribute.
so if performance is an issue - use "setAttributeNode"
#define DEBUG
#ifdef DEBUG
#define PRINT print
#else
#define PRINT(...) ((void)0) //strip out PRINT instructions from code
#endif
void print(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vsprintf(str, fmt, args);
va_end(args);
printf("%s\n", str);
}
int main() {
PRINT("[%s %d, %d] Hello World", "March", 26, 2009);
return 0;
}
If the compiler does not understand variadic macros, you can also strip out PRINT with either of the following:
#define PRINT //
or
#define PRINT if(0)print
The first comments out the PRINT instructions, the second prevents PRINT instruction because of a NULL if condition. If optimization is set, the compiler should strip out never executed instructions like: if(0) print("hello world"); or ((void)0);
Although answer is provided I found simpler solution:
Date:
01/20/2017
By doing replace
CurrentDate = replace(date, "/", "-")
It will output:
01-20-2017
You can create a script to switch from versions: sudo nano switch_php
then type this:
#!/bin/sh
#!/bin/bash
echo "Switching to PHP$1..."
case $1 in
"7")
sudo a2dismod php5.6
sudo a2enmod php7.0
sudo service apache2 restart
sudo ln -sfn /usr/bin/php7.0 /etc/alternatives/php;;
"5.6")
sudo a2dismod php7.0
sudo a2enmod php5.6
sudo service apache2 restart
sudo ln -sfn /usr/bin/php5.6 /etc/alternatives/php;;
esac
echo "Current version: $( php -v | head -n 1 | cut -c-7 )"
exit and save
make it executable: sudo chmod +x switch_php
To execute the script just type ./switch_php [VERSION_NUMBER]
where the parameter is 7 or 5.6
That's it you can now easily switch form PHP7 to PHP 5.6!
RIGHT ( character_expression , integer_expression )
SELECT RIGHT(column, 4) FROM ...
Also a list of other string functions.
There's more than one way to do it:
select 1 where datediff(second, '2010-07-20 03:21:52', '2010-07-20 03:21:52.577') >= 0
or
select *
from table
where datediff(second, '2010-07-20 03:21:52', date) >= 0
one less function call, but you have to be beware of overflowing the max integer if the dates are too far apart.
Using name on a select option is not valid.
Other have suggested the data- attribute, an alternative is a lookup table
Here the "this" refers to the select so no need to "find" the option
var names = ["", "acoustic", "jazz", "acoustic_jazz", "party", "acoustic_party", "jazz_party", "acoustic_jazz_party"];_x000D_
_x000D_
$(function() {_x000D_
$('#band_type_choices').on('change', function() {_x000D_
$('.checkboxlist').hide();_x000D_
var idx = this.selectedIndex;_x000D_
if (idx > 0) $('#checkboxlist_' + names[idx]).show();_x000D_
});_x000D_
});
_x000D_
.checkboxlist { display:none }
_x000D_
Choose acoustic to see the corresponding div_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="band_type_choices">_x000D_
<option vlaue="0"></option>_x000D_
<option value="100" name="acoustic">Acoustic</option>_x000D_
<option value="0" name="jazz">Jazz/Easy Listening</option>_x000D_
<option value="0" name="acoustic_jazz">Acoustic + Jazz/Easy Listening</option>_x000D_
<option value="0" name="party">Party</option>_x000D_
<option value="0" name="acoustic_party">Acoustic + Party</option>_x000D_
<option value="0" name="jazz_party">Jazz/Easy Listening + Party</option>_x000D_
<option value="0" name="acoustic_jazz_party">Acoustic + Jazz/Easy Listening + Party</option>_x000D_
</select>_x000D_
<div class="checkboxlist" id="checkboxlist_acoustic">_x000D_
<input type="checkbox" class="checkbox keys" name="keys" value="100" />Keys<br>_x000D_
<input type="checkbox" class="checkbox acou_guit" name="acou_guit" value="100" />Acoustic Guitar<br>_x000D_
<input type="checkbox" class="checkbox drums" name="drums" value="100" />Drums<br>_x000D_
<input type="checkbox" class="checkbox alt_sax" name="alt_sax" value="100" />Alto Sax<br>_x000D_
<input type="checkbox" class="checkbox ten_sax" name="ten_sax" value="100" />Tenor Sax<br>_x000D_
<input type="checkbox" class="checkbox clarinet" name="clarinet" value="100" />Clarinet<br>_x000D_
<input type="checkbox" class="checkbox trombone" name="trombone" value="100" />Trombone<br>_x000D_
<input type="checkbox" class="checkbox trumpet" name="trumpet" value="100" />Trumpet<br>_x000D_
<input type="checkbox" class="checkbox flute" name="flute" value="100" />Flute<br>_x000D_
<input type="checkbox" class="checkbox cello" name="cello" value="100" />Cello<br>_x000D_
<input type="checkbox" class="checkbox violin" name="violin" value="100" />Violin<br>_x000D_
</div>
_x000D_
cursor:pointer
doesn't work when you're using Chrome's mobile emulator.
Try to declare UseHttpGet over your method.
[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
return "Hello World";
}
Syntax
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Parameters
start
: required. Initial index.start
is negative it is treated as "Math.max((array.length + start), 0)"
as per spec (example provided below) effectively from the end of array
.deleteCount
: optional. Number of elements to be removed (all from start
if not provided).item1, item2, ...
: optional. Elements to be added to the array from start
index.Returns: An array with deleted elements (empty array if none removed)
Mutate original array: Yes
const array = [1,2,3,4,5];
// Remove first element
console.log('Elements deleted:', array.splice(0, 1), 'mutated array:', array);
// Elements deleted: [ 1 ] mutated array: [ 2, 3, 4, 5 ]
// array = [ 2, 3, 4, 5]
// Remove last element (start -> array.length+start = 3)
console.log('Elements deleted:', array.splice(-1, 1), 'mutated array:', array);
// Elements deleted: [ 5 ] mutated array: [ 2, 3, 4 ]
_x000D_
More examples in MDN Splice examples
Syntax
array.slice([begin[, end]])
Parameters
begin
: optional. Initial index (default 0).begin
is negative it is treated as "Math.max((array.length + begin), 0)"
as per spec (example provided below) effectively from the end of array
.end
: optional. Last index for extraction but not including (default array.length). If end
is negative it is treated as "Math.max((array.length + begin),0)"
as per spec (example provided below) effectively from the end of array
.Returns: An array containing the extracted elements.
Mutate original: No
const array = [1,2,3,4,5];
// Extract first element
console.log('Elements extracted:', array.slice(0, 1), 'array:', array);
// Elements extracted: [ 1 ] array: [ 1, 2, 3, 4, 5 ]
// Extract last element (start -> array.length+start = 4)
console.log('Elements extracted:', array.slice(-1), 'array:', array);
// Elements extracted: [ 5 ] array: [ 1, 2, 3, 4, 5 ]
_x000D_
More examples in MDN Slice examples
Don't take this as absolute truth as depending on each scenario one might be performant than the other.
Performance test
In my case, I had the variable named "AWS_PROFILE" on Environment variables with an old value.
<script language="JavaScript" type="text/javascript">
<!--
function loopSelected()
{
var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
var selectedArray = new Array();
var selObj = document.getElementById('selSeaShells');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'Tutorial004NewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'Tutorial004NewWindow';
// submit
frm.submit();
}
//-->
</script>
The HTML
<form action="tutorial004_nw.html" method="get">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<td valign="top">
<input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
<input type="button" value="Loop Selected" onclick="loopSelected();" />
<br />
<select name="selSea" id="selSeaShells" size="5" multiple="multiple">
<option value="val0" selected>sea zero</option>
<option value="val1">sea one</option>
<option value="val2">sea two</option>
<option value="val3">sea three</option>
<option value="val4">sea four</option>
</select>
</td>
<td valign="top">
<input type="text" id="txtSelectedValues" />
selected array
</td>
</tr>
</table>
</form>
replace
works for the first quote, so you need a tiny regular expression:
str = str.replace(/'/g, "\\'");
Many answers already, but none of them perfect IMHO. Thanatos' answer leaves some extra characters per line and Sorpigal's answer requires the files to be sorted or pre-sorted, which may not be adequate in all circumstances.
I think the best way of getting the lines that are different and nothing else (no extra chars, no re-ordering) is a combination of diff
, grep
, and awk
(or similar).
If the lines do not contain any "<", a short one-liner can be:
diff urls.txt* | grep "<" | sed 's/< //g'
but that will remove every instance of "< " (less than, space) from the lines, which is not always OK (e.g. source code). The safest option is to use awk:
diff urls.txt* | grep "<" | awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}'
This one-liner diffs both files, then filters out the ed-style output of diff, then removes the trailing "<" that diff adds. This works even if the lines contains some "<" themselves.
As of today, you can read some values from HTML5 data
attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data
properties for setting the content
.
Unfortunately it is not working for the width
and height
(tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).
But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width
and data-height
. You can find the GitHub repo to it here: cssattr.js.
Is JSTL's join()
, what you searched for?
<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />
If you have removed package using Uninstall-Package utility and deleted the desired package from package directory under solution (and you are still getting error), just open up the *.csproj file in code editor and remove the tag manually. Like for instance, I wanted to get rid of Nuget package Xamarin.Forms.Alias and I removed these lines from *.csproj file.
And finally, don't forget to reload your project once prompted in Visual Studio (after changing project file). I tried it on Visual Studio 2015, but it should work on Visual Studio 2010 and onward too.
Hope this helps.
use this code
window.onhashchange = function() {
//code
}
with jQuery
$(window).bind('hashchange', function() {
//code
});
I had the same problem: I love the resolve
object, but that only works for the content of ng-view. What if you have controllers (for top-level nav, let's say) that exist outside of ng-view and which need to be initialized with data before the routing even begins to happen? How do we avoid mucking around on the server-side just to make that work?
Use manual bootstrap and an angular constant. A naiive XHR gets you your data, and you bootstrap angular in its callback, which deals with your async issues. In the example below, you don't even need to create a global variable. The returned data exists only in angular scope as an injectable, and isn't even present inside of controllers, services, etc. unless you inject it. (Much as you would inject the output of your resolve
object into the controller for a routed view.) If you prefer to thereafter interact with that data as a service, you can create a service, inject the data, and nobody will ever be the wiser.
Example:
//First, we have to create the angular module, because all the other JS files are going to load while we're getting data and bootstrapping, and they need to be able to attach to it.
var MyApp = angular.module('MyApp', ['dependency1', 'dependency2']);
// Use angular's version of document.ready() just to make extra-sure DOM is fully
// loaded before you bootstrap. This is probably optional, given that the async
// data call will probably take significantly longer than DOM load. YMMV.
// Has the added virtue of keeping your XHR junk out of global scope.
angular.element(document).ready(function() {
//first, we create the callback that will fire after the data is down
function xhrCallback() {
var myData = this.responseText; // the XHR output
// here's where we attach a constant containing the API data to our app
// module. Don't forget to parse JSON, which `$http` normally does for you.
MyApp.constant('NavData', JSON.parse(myData));
// now, perform any other final configuration of your angular module.
MyApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/someroute', {configs})
.otherwise({redirectTo: '/someroute'});
}]);
// And last, bootstrap the app. Be sure to remove `ng-app` from your index.html.
angular.bootstrap(document, ['NYSP']);
};
//here, the basic mechanics of the XHR, which you can customize.
var oReq = new XMLHttpRequest();
oReq.onload = xhrCallback;
oReq.open("get", "/api/overview", true); // your specific API URL
oReq.send();
})
Now, your NavData
constant exists. Go ahead and inject it into a controller or service:
angular.module('MyApp')
.controller('NavCtrl', ['NavData', function (NavData) {
$scope.localObject = NavData; //now it's addressable in your templates
}]);
Of course, using a bare XHR object strips away a number of the niceties that $http
or JQuery would take care of for you, but this example works with no special dependencies, at least for a simple get
. If you want a little more power for your request, load up an external library to help you out. But I don't think it's possible to access angular's $http
or other tools in this context.
(SO related post)
Here's an example of the string "abc" repeated
3 times:
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;
int main() {
ostringstream repeated;
fill_n(ostream_iterator<string>(repeated), 3, string("abc"));
cout << "repeated: " << repeated.str() << endl; // repeated: abcabcabc
return 0;
}
You can specify a new column. You also need to compute the mean along the rows, so use axis=1
.
df['mean'] = df.mean(axis=1)
>>> df
Y1961 Y1962 Y1963 Y1964 Y1965 Region mean
0 82.567307 83.104757 83.183700 83.030338 82.831958 US 82.943612
1 2.699372 2.610110 2.587919 2.696451 2.846247 US 2.688020
2 14.131355 13.690028 13.599516 13.649176 13.649046 US 13.743824
3 0.048589 0.046982 0.046583 0.046225 0.051750 US 0.048026
4 0.553377 0.548123 0.582282 0.577811 0.620999 US 0.576518
If you truly want to "grep" the formatted output (display strings) then go with Mike's approach. There are definitely times where this comes in handy. However if you want to try embracing PowerShell's object pipeline nature, then try this. First, check out the properties on the objects flowing down the pipeline:
PS> alias | Get-Member
TypeName: System.Management.Automation.AliasInfo
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
<snip>
*Definition* Property System.String Definition {get;}
<snip>
Note the Definition property which is a header you see when you display the output of Get-Alias (alias) e.g.:
PS> alias
CommandType Name *Definition*
----------- ---- ----------
Alias % ForEach-Object
<snip>
Usually the header title matches the property name but not always. That is where using Get-Member comes in handy. It shows you what you need to "script" against. Now if what you want to "grep" is the Definition property contents then consider this. Rather than just grepping that one property's value, you can instead filter each AliasInfo object in the pipepline by the contents of this property and you can use a regex to do it e.g.:
PS> alias | Where-Object {$_.Definition -match 'alias'}
CommandType Name Definition
----------- ---- ----------
Alias epal Export-Alias
Alias gal Get-Alias
Alias ipal Import-Alias
Alias nal New-Alias
Alias sal Set-Alias
In this example I use the Where-Object cmdlet to filter objects based on some arbitrary script. In this case, I filter by the Defintion property matched against the regex 'alias'. Only those objects that return true for that filter are allowed to propagate down the pipeline and get formatted for display on the host.
BTW if you're typing this, then you can use one of two aliases for Where-Object - 'Where' or '?'. For example:
PS> gal | ?{$_.Definition -match '-Item*'}
Doing this yourself will give you insight into how a WSDL is structured and how it gets your job done. It is a good learning opportunity. This can be done using soapUI, if you only have the URL of the WSDL. (I'm using soapUI 5.2.1) If you actually have the complete WSDL as a file available to you, you don't even need soapUI. The title of the question says "Request & Response XML" while the question body says "Request & Response XML formats" which I interpret as the schema of the request and response. At any rate, the following will give you the schema which you can use on XSD2XML to generate sample XML.
<s:element name="GetWeather">
and ends with </s:element>
.
<?xml version="1.0" encoding="UTF-8"?>
<s:schema xmlns:s="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
</s:schema>
You can try above procedure out using the WSDL at http://www.webservicex.com/globalweather.asmx?wsdl
For me worked only adding the config
or ssh_config
file that was on the dir ~/.ssh/config
on my Linux system on the c:\Program Files\Git\etc\ssh\
directory on Windows.
In some git versions we need to edit the C:\Users\<username>\AppData\Local\Programs\Git\etc\ssh\ssh_config
file.
After that, I was able to use all the alias and settings that I normally used on my Linux connecting or pushing via SSH on the Git Bash.
I've used a mixture of solutions described above:
$ git branch temp <specific sha1>
$ git rebase --onto temp master topic
$ git branch -d temp
I found it much easier to read and understand. The accepted solution lead me to a merge conflict (too lazy to fix by hand):
$ git rebase temp
First, rewinding head to replay your work on top of it...
Applying: <git comment>
Using index info to reconstruct a base tree...
M pom.xml
.git/rebase-apply/patch:10: trailing whitespace.
<some code>
.git/rebase-apply/patch:17: trailing whitespace.
<some other code>
warning: 2 lines add whitespace errors.
Falling back to patching base and 3-way merge...
Auto-merging pom.xml
CONFLICT (content): Merge conflict in pom.xml
error: Failed to merge in the changes.
Patch failed at 0001 <git comment>
The copy of the patch that failed is found in: .git/rebase-apply/patch
When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".
For a checked exception:
public class MyCustomException extends Exception { }
Technically, anything that extends Throwable
can be an thrown, but exceptions are generally extensions of the Exception
class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Error
s which usually are not something designed to be gracefully handled beyond the JVM internals.
You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.
As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via
throw new MyCustomException()
and catch via
catch (MyCustomException e) { }
In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.
In this case, you don't need to add any wrapper functions around lists.
It is possible to write an HTML string in JSON. You just need to escape your double-quotes.
[
{
"id": "services.html",
"img": "img/SolutionInnerbananer.jpg",
"html": "<h2class=\"fg-white\">AboutUs</h2><pclass=\"fg-white\">CSMTechnologiesisapioneerinprovidingconsulting,
developingandsupportingcomplexITsolutions.Touchingmillionsoflivesworldwidebybringingininnovativetechnology,
CSMforayedintotheuntappedmarketslikee-GovernanceinIndiaandAfricancontinent.</p>"
}
]
In the .content
tab in CSS change it to position:absolute
. Otherwise, the page rendered won't be scrollable.
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
The most simply you can do it is :
git commit -am "Your commit message"
I dont understand why are we making this tricky.
So you are doing the right thing concerning "-XX:MaxPermSize=512m": it is indeed the correct syntax. You could try to set these options directly to the Catalyna server files so they are used on server start.
Maybe this post will help you!
How to make sure that Tomcat6 reads CATALINA_OPTS on Windows?
See mozilla.org's write-up on how CORS works.
You'll need your server to send back the proper response headers, something like:
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Bear in mind you can use "*"
for Access-Control-Allow-Origin
that will only work if you're trying to pass Authentication data. In that case, you need to explicitly list the origin domains you want to allow. To allow multiple domains, see this post
I just saw this test:
bool getFileExists(const TCHAR *file)
{
return (GetFileAttributes(file) != 0xFFFFFFFF);
}
For PHP 5.3 this should work. You may need to fiddle with passing $dateInfo['is_dst'], wasn't working for me anyhow.
$date = '05/Feb/2010:14:00:01';
$dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
$dateInfo['month'], $dateInfo['day'], $dateInfo['year'],
$dateInfo['is_dst']
);
Versions prior, this should work.
$date = '05/Feb/2010:14:00:01';
$format = '@^(?P<day>\d{2})/(?P<month>[A-Z][a-z]{2})/(?P<year>\d{4}):(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})$@';
preg_match($format, $date, $dateInfo);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
date('n', strtotime($dateInfo['month'])), $dateInfo['day'], $dateInfo['year'],
date('I')
);
You may not like regular expressions. You could annotate it, of course, but not everyone likes that either. So, this is an alternative.
$day = $date[0].$date[1];
$month = date('n', strtotime($date[3].$date[4].$date[5]));
$year = $date[7].$date[8].$date[9].$date[10];
$hour = $date[12].$date[13];
$minute = $date[15].$date[16];
$second = $date[18].$date[19];
Or substr, or explode, whatever you wish to parse that string.
Try this:
require 'open-uri'
open('image.png', 'wb') do |file|
file << open('http://example.com/image.png').read
end
You can't.
The only way to get a list of all event listeners attached to a node is to intercept the listener attachment call.
Says
Append an event listener to the associated list of event listeners with type set to type, listener set to listener, and capture set to capture, unless there already is an event listener in that list with the same type, listener, and capture.
Meaning that an event listener is added to the "list of event listeners". That's all. There is no notion of what this list should be nor how you should access it.
Swift 5
This works for cocoa
let bundleRoot = Bundle.main.bundlePath
let manager = FileManager.default
let dirEnum = manager.enumerator(atPath: bundleRoot)
while let filename = dirEnum?.nextObject() as? String {
if filename.hasSuffix(".data"){
print("Files in resource folder: \(filename)")
}
}
I have done it using AutotextView
:
AutotextView textView = (AutotextView) findViewById(R.id.autotextview);
textView.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
seq = cs;
}
@Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
}
@Override
public void afterTextChanged(Editable arg0) {
new SearchTask().execute(seq.toString().trim());
}
});
Environment.GetCommandLineArgs()[0]
C# 6 adds a new feature just for this: extension Add methods. This has always been possible for VB.net but is now available in C#.
Now you don't have to add Add()
methods to your classes directly, you can implement them as extension methods. When extending any enumerable type with an Add()
method, you'll be able to use it in collection initializer expressions. So you don't have to derive from lists explicitly anymore (as mentioned in another answer), you can simply extend it.
public static class TupleListExtensions
{
public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
T1 item1, T2 item2)
{
list.Add(Tuple.Create(item1, item2));
}
public static void Add<T1, T2, T3>(this IList<Tuple<T1, T2, T3>> list,
T1 item1, T2 item2, T3 item3)
{
list.Add(Tuple.Create(item1, item2, item3));
}
// and so on...
}
This will allow you to do this on any class that implements IList<>
:
var numbers = new List<Tuple<int, string>>
{
{ 1, "one" },
{ 2, "two" },
{ 3, "three" },
{ 4, "four" },
{ 5, "five" },
};
var points = new ObservableCollection<Tuple<double, double, double>>
{
{ 0, 0, 0 },
{ 1, 2, 3 },
{ -4, -2, 42 },
};
Of course you're not restricted to extending collections of tuples, it can be for collections of any specific type you want the special syntax for.
public static class BigIntegerListExtensions
{
public static void Add(this IList<BigInteger> list,
params byte[] value)
{
list.Add(new BigInteger(value));
}
public static void Add(this IList<BigInteger> list,
string value)
{
list.Add(BigInteger.Parse(value));
}
}
var bigNumbers = new List<BigInteger>
{
new BigInteger(1), // constructor BigInteger(int)
2222222222L, // implicit operator BigInteger(long)
3333333333UL, // implicit operator BigInteger(ulong)
{ 4, 4, 4, 4, 4, 4, 4, 4 }, // extension Add(byte[])
"55555555555555555555555555555555555555", // extension Add(string)
};
C# 7 will be adding in support for tuples built into the language, though they will be of a different type (System.ValueTuple
instead). So to it would be good to add overloads for value tuples so you have the option to use them as well. Unfortunately, there are no implicit conversions defined between the two.
public static class ValueTupleListExtensions
{
public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
ValueTuple<T1, T2> item) => list.Add(item.ToTuple());
}
This way the list initialization will look even nicer.
var points = new List<Tuple<int, int, int>>
{
(0, 0, 0),
(1, 2, 3),
(-1, 12, -73),
};
But instead of going through all this trouble, it might just be better to switch to using ValueTuple
exclusively.
var points = new List<(int, int, int)>
{
(0, 0, 0),
(1, 2, 3),
(-1, 12, -73),
};
put this inside your Manifest like this in No fullscreen Mode
android:windowSoftInputMode="stateVisible|adjustPan"
in your manifest
<activity
android:windowSoftInputMode="stateVisible|adjustPan"
android:name="com.example.patronusgps.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
It may be nicer one to use slice like :
string.slice(1, -1)
you may add an interceptor .
myModule.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('noCacheInterceptor');
}]).factory('noCacheInterceptor', function () {
return {
request: function (config) {
console.log(config.method);
console.log(config.url);
if(config.method=='GET'){
var separator = config.url.indexOf('?') === -1 ? '?' : '&';
config.url = config.url+separator+'noCache=' + new Date().getTime();
}
console.log(config.method);
console.log(config.url);
return config;
}
};
});
you should remove console.log lines after verifying.
Let's assume that your iframe id= myIframe
here is the code:
<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
document.getElementById("myIframe").src="YOUR_PAGE_URL_HERE";
}
</script>
DateTime.Now.Date.ToShortDateString()
is culture specific.
It is best to stick with:
DateTime.Now.ToString("d/MM/yyyy");
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
As a new scala developer i wrote small test to check list creation time with suggested methods above. It looks like (for ( p <- ( 0 to x ) ) yield p) toList the fastest approach.
import java.util.Date
object Listbm {
final val listSize = 1048576
final val iterationCounts = 5
def getCurrentTime: BigInt = (new Date) getTime
def createList[T] ( f : Int => T )( size : Int ): T = f ( size )
// returns function time execution
def experiment[T] ( f : Int => T ) ( iterations: Int ) ( size :Int ) : Int = {
val start_time = getCurrentTime
for ( p <- 0 to iterations ) createList ( f ) ( size )
return (getCurrentTime - start_time) toInt
}
def printResult ( f: => Int ) : Unit = println ( "execution time " + f )
def main( args : Array[String] ) {
args(0) match {
case "for" => printResult ( experiment ( x => (for ( p <- ( 0 to x ) ) yield p) toList ) ( iterationCounts ) ( listSize ) )
case "range" => printResult ( experiment ( x => ( 0 to x ) toList ) ( iterationCounts ) ( listSize ) )
case "::" => printResult ( experiment ( x => ((0 to x) :\ List[Int]())(_ :: _) ) ( iterationCounts ) ( listSize ) )
case _ => println ( "please use: for, range or ::\n")
}
}
}
Please use regex to remove anything before |
example
dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds
Use find and replace in notepad++
find: .+(\|)
replace: \1
output
| fdfsfsf
|gfghhghg
|dfdsfsds
So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:
>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:id="@+id/your_id"
android:layout_marginTop="160dp" />
I guess you are actually using Amazon Linux AMI 2013.03.1 instead of Ubuntu Server 12.x reason why you don't have apt-get tool installed.
In your giant elif
chain, you skipped 13. You might want to throw an error if you hit the end of the chain without returning anything, to catch numbers you missed and incorrect calls of the function:
...
elif x == 90:
return 6
else:
raise ValueError(x)
I just used:
import java.nio.file.Path;
import java.nio.file.Paths;
...
Path workingDirectory=Paths.get(".").toAbsolutePath();
A reset will normally change everything, but you can use git stash
to pick what you want to keep. As you mentioned, stash
doesn't accept a path directly, but it can still be used to keep a specific path with the --keep-index
flag. In your example, you would stash the b directory, then reset everything else.
# How to make files a/* reappear without changing b and without recreating a/c?
git add b #add the directory you want to keep
git stash --keep-index #stash anything that isn't added
git reset #unstage the b directory
git stash drop #clean up the stash (optional)
This gets you to a point where the last part of your script will output this:
After checkout:
# On branch master
# Changes not staged for commit:
#
# modified: b/a/ba
#
no changes added to commit (use "git add" and/or "git commit -a")
a/a/aa
a/b/ab
b/a/ba
I believe this was the target result (b remains modified, a/* files are back, a/c is not recreated).
This approach has the added benefit of being very flexible; you can get as fine-grained as you want adding specific files, but not other ones, in a directory.
You can get data from post response Headers in this way (Angular 6):
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response' as 'response'
};
this.http.post(link,body,httpOptions).subscribe((res: HttpResponse<any>) => {
console.log(res.headers.get('token-key-name'));
})
You can configure HttpClient
to automatically pass credentials like this:
var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
If you don't like break
s and goto
s, you can use a "traditional" for loop instead the for-in, with an extra abort condition:
int a, b;
bool abort = false;
for (a = 0; a < 10 && !abort; a++) {
for (b = 0; b < 10 && !abort; b++) {
if (condition) {
doSomeThing();
abort = true;
}
}
}
I believe "swapnesh" answer to be the best ! Unfortunately I couldn't execute it in phpMyAdmin (4.5.0.2) who although illogical (and tried several things) it kept saying that a new statement was found and that no delimiter was found…
Thus I came with the following solution that might be usefull if you exeprience the same issue and have no other access to the database than PMA…
UPDATE `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid`
FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
SET `toUpdate`.`guid`=`updated`.`guid`
WHERE `toUpdate`.`ID`=`updated`.`ID`;
To test the expected result you may want to use :
SELECT `toUpdate`.`guid` AS `old guid`,`updated`.`guid` AS `new guid`
FROM `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid`
FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
WHERE `toUpdate`.`ID`=`updated`.`ID`;
Simple socket server app example
I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.
This example app runs a server that returns a ROT-1 cypher of the input.
You would then need to add an Exit
button + some sleep delays, but this should get you started.
To play with it:
netcat $PHONE_IP 12345
Android sockets are the same as Java's, except we have to deal with some permission issues.
src/com/cirosantilli/android_cheat/socket/Main.java
package com.cirosantilli.android_cheat.socket;
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main extends Activity {
static final String TAG = "AndroidCheatSocket";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Main.TAG, "onCreate");
Main.this.startService(new Intent(Main.this, MyService.class));
}
public static class MyService extends IntentService {
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(Main.TAG, "onHandleIntent");
final int port = 12345;
ServerSocket listener = null;
try {
listener = new ServerSocket(port);
Log.d(Main.TAG, String.format("listening on port = %d", port));
while (true) {
Log.d(Main.TAG, "waiting for client");
Socket socket = listener.accept();
Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(socket.getOutputStream());
for (String inputLine; (inputLine = in.readLine()) != null;) {
Log.d(Main.TAG, "received");
Log.d(Main.TAG, inputLine);
StringBuilder outputStringBuilder = new StringBuilder("");
char inputLineChars[] = inputLine.toCharArray();
for (char c : inputLineChars)
outputStringBuilder.append(Character.toChars(c + 1));
out.println(outputStringBuilder);
}
}
} catch(IOException e) {
Log.d(Main.TAG, e.toString());
}
}
}
}
We need a Service
or other background method or else: How do I fix android.os.NetworkOnMainThreadException?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cirosantilli.android_cheat.socket"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="AndroidCheatsocket">
<activity android:name="Main">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Main$MyService" />
</application>
</manifest>
We must add: <uses-permission android:name="android.permission.INTERNET" />
or else: Java socket IOException - permission denied
On GitHub with a build.xml
: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket
Two possible approaches.
If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.
Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?
delete from child_table
where parent_id in (
select parent_id from parent_table
where updd_tms != (sysdate-30)
-- now delete the parent table records
delete from parent_table
where updd_tms != (sysdate-30);
---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).
declare
v_sqlcode number;
PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
for v_rec in (select parent_id, child id from child_table
where updd_tms != (sysdate-30) ) loop
-- delete the children
delete from child_table where child_id = v_rec.child_id;
-- delete the parent. If we get foreign key violation,
-- stop this step and continue the loop
begin
delete from parent_table
where parent_id = v_rec.parent_id;
exception
when foreign_key_violated
then null;
end;
end loop;
end;
/
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
Often this question is asked in the context of Ron de Bruin's RangeToHTML
function, which creates an HTML PublishObject
from an Excel.Range
, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody
. In doing so, this removes the default signature (the RangeToHTML
function has a helper function GetBoiler
which attempts to insert the default signature).
Unfortunately, the poorly-documented Application.CommandBars
method is not available via Outlook:
wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"
It will raise a runtime 6158:
But we can still leverage the Word.Document
which is accessible via the MailItem.GetInspector
method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).
Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed
With OutMail
.To = "[email protected]"
.BCC = ""
.Subject = "Subject"
.Display
Dim wdDoc As Object '## Word.Document
Dim wdRange As Object '## Word.Range
Set wdDoc = OutMail.GetInspector.WordEditor
Set wdRange = wdDoc.Range(0, 0)
wdRange.InsertAfter vbCrLf & vbCrLf
'Copy the range in-place
rng.Copy
wdRange.Paste
End With
Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:
A lot of years after... I like this one:
For x = LBound(arr) To UBound(arr): Do
sname = arr(x)
If instr(sname, "Configuration item") Then Exit Do
'// other code to copy past and do various stuff
Loop While False: Next x
There is a check placed at Yarn level for Virtual and Physical memory usage ratio. Issue is not only that VM doesn't have sufficient physical memory. But it is because Virtual memory usage is more than expected for given physical memory.
Note : This is happening on Centos/RHEL 6 due to its aggressive allocation of virtual memory.
It can be resolved either by :
Disable virtual memory usage check by setting yarn.nodemanager.vmem-check-enabled to false;
Increase VM:PM ratio by setting yarn.nodemanager.vmem-pmem-ratio to some higher value.
References :
https://issues.apache.org/jira/browse/HADOOP-11364
http://blog.cloudera.com/blog/2014/04/apache-hadoop-yarn-avoiding-6-time-consuming-gotchas/
Add following property in yarn-site.xml
<property>
<name>yarn.nodemanager.vmem-check-enabled</name>
<value>false</value>
<description>Whether virtual memory limits will be enforced for containers</description>
</property>
<property>
<name>yarn.nodemanager.vmem-pmem-ratio</name>
<value>4</value>
<description>Ratio between virtual memory to physical memory when setting memory limits for containers</description>
</property>
What about using checkout command :
git diff --stat "$branch"
git checkout --merge "$branch" "$file"
git diff --stat "$branch"
It's simple. Just do this:
#include <iostream>
#include <vector>
#include <string.h>
int main(int argc, char *argv[])
{
std::vector<std::string> argList;
for(int i=0;i<argc;i++)
argList.push_back(argv[i]);
//now you can access argList[n]
}
@Benjamin Lindley You are right. This is not a good solution. Please read the one answered by juanchopanza.
Use jQuery's $.param
function to serialize the JSON data in requestData.
In short, using similar code as yours:
$http.post("/foo/bar",
$.param(requestData),
{
headers:
{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}
).success(
function(responseData) {
//do stuff with response
}
});
For using this, you have to include jQuery in your page along with AngularJS.
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
I ran into this recently and eventually found that this was caused by a network timeout from the endpoint we were hitting. Fortunately for us we were able to increase the timeout duration.
To verify this was our issue (and actually not an issue with net http), I made the same request with curl and confirmed that the request was being terminated.
You could do something like this:
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys() #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")] #'foo'
However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.
As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.
Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:
d={'i':1, 'j':1}
In that case, it is impossible to know whether you want i
or j
and in fact no answer here will be able to tell you which ('i'
or 'j'
) will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.
Here is a function to get the IP address using a filter for local and LAN IP addresses:
function get_IP_address()
{
foreach (array('HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $IPaddress){
$IPaddress = trim($IPaddress); // Just to be safe
if (filter_var($IPaddress,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
!== false) {
return $IPaddress;
}
}
}
}
}
You can use the event.target.result to reset the input from a component directly.
event.target.value = ""
To display a dialog or a toaster in a thread, the most concise way is to use the Activity object.
For example:
new Thread(new Runnable() {
@Override
public void run() {
myActivity.runOnUiThread(new Runnable() {
public void run() {
myActivity.this.processingWaitDialog = new ProgressDialog(myActivity.this.getContext());
myActivity.this.processingWaitDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
myActivity.this.processingWaitDialog.setMessage("abc");
myActivity.this.processingWaitDialog.setIndeterminate(true);
myActivity.this.processingWaitDialog.show();
}
});
expenseClassify.serverPost(
new AsyncOperationCallback() {
public void operationCompleted(Object sender) {
myActivity.runOnUiThread(new Runnable() {
public void run() {
if (myActivity.this.processingWaitDialog != null
&& myActivity.this.processingWaitDialog.isShowing()) {
myActivity.this.processingWaitDialog.dismiss();
myActivity.this.processingWaitDialog = null;
}
}
}); // .runOnUiThread(new Runnable()
...
Why not simply set it up as a Scheduled Task that is scheduled to run at start up?
The raw.githubusercontent.com
domain is used to serve unprocessed versions of files stored in GitHub repositories. If you browse to a file on GitHub and then click the Raw link, that's where you'll go.
The URL in your question references the install
file in the master
branch of the Homebrew/install
repository. The rest of that command just retrieves the file and runs ruby
on its contents.
So I was curious about the performance of some of the methods mentioned in the answers for large number of integers.
Just creating an array of 1 million random integers between 0 and 100. Than, I imploded them to get the string.
$integers = array();
for ($i = 0; $i < 1000000; $i++) {
$integers[] = rand(0, 100);
}
$long_string = implode(',', $integers);
This is the one liner from Mark's answer:
$integerIDs = array_map('intval', explode(',', $long_string));
This is the JSON approach:
$integerIDs = json_decode('[' . $long_string . ']', true);
I came up with this one as modification of Mark's answer. This is still using explode()
function, but instead of calling array_map()
I'm using regular foreach
loop to do the work to avoid the overhead array_map()
might have. I am also parsing with (int)
vs intval()
, but I tried both, and there is not much difference in terms of performance.
$result_array = array();
$strings_array = explode(',', $long_string);
foreach ($strings_array as $each_number) {
$result_array[] = (int) $each_number;
}
Results:
Method 1 Method 2 Method 3
0.4804770947 0.3608930111 0.3387751579
0.4748001099 0.363986969 0.3762528896
0.4625790119 0.3645150661 0.3335959911
0.5065748692 0.3570590019 0.3365750313
0.4803431034 0.4135499001 0.3330330849
0.4510772228 0.4421861172 0.341176033
0.503674984 0.3612480164 0.3561749458
0.5598649979 0.352314949 0.3766179085
0.4573421478 0.3527538776 0.3473439217
0.4863037268 0.3742785454 0.3488383293
The bottom line is the average. It looks like the first method was a little slower for 1 million integers, but I didn't notice 3x performance gain of Method 2 as stated in the answer. It turned out foreach
loop was the quickest one in my case. I've done the benchmarking with Xdebug.
Edit: It's been a while since the answer was originally posted. To clarify, the benchmark was done in php 5.6.
Use This [Tested]
To get numeric
SELECT column1
FROM table
WHERE Isnumeric(column1) = 1; // will return Numeric values
To get non-numeric
SELECT column1
FROM table
WHERE Isnumeric(column1) = 0; // will return non-numeric values
The Dir function is the way to go, but the problem is that you cannot use the Dir
function recursively, as stated here, towards the bottom.
The way that I've handled this is to use the Dir
function to get all of the sub-folders for the target folder and load them into an array, then pass the array into a function that recurses.
Here's a class that I wrote that accomplishes this, it includes the ability to search for filters. (You'll have to forgive the Hungarian Notation, this was written when it was all the rage.)
Private m_asFilters() As String
Private m_asFiles As Variant
Private m_lNext As Long
Private m_lMax As Long
Public Function GetFileList(ByVal ParentDir As String, Optional ByVal sSearch As String, Optional ByVal Deep As Boolean = True) As Variant
m_lNext = 0
m_lMax = 0
ReDim m_asFiles(0)
If Len(sSearch) Then
m_asFilters() = Split(sSearch, "|")
Else
ReDim m_asFilters(0)
End If
If Deep Then
Call RecursiveAddFiles(ParentDir)
Else
Call AddFiles(ParentDir)
End If
If m_lNext Then
ReDim Preserve m_asFiles(m_lNext - 1)
GetFileList = m_asFiles
End If
End Function
Private Sub RecursiveAddFiles(ByVal ParentDir As String)
Dim asDirs() As String
Dim l As Long
On Error GoTo ErrRecursiveAddFiles
'Add the files in 'this' directory!
Call AddFiles(ParentDir)
ReDim asDirs(-1 To -1)
asDirs = GetDirList(ParentDir)
For l = 0 To UBound(asDirs)
Call RecursiveAddFiles(asDirs(l))
Next l
On Error GoTo 0
Exit Sub
ErrRecursiveAddFiles:
End Sub
Private Function GetDirList(ByVal ParentDir As String) As String()
Dim sDir As String
Dim asRet() As String
Dim l As Long
Dim lMax As Long
If Right(ParentDir, 1) <> "\" Then
ParentDir = ParentDir & "\"
End If
sDir = Dir(ParentDir, vbDirectory Or vbHidden Or vbSystem)
Do While Len(sDir)
If GetAttr(ParentDir & sDir) And vbDirectory Then
If Not (sDir = "." Or sDir = "..") Then
If l >= lMax Then
lMax = lMax + 10
ReDim Preserve asRet(lMax)
End If
asRet(l) = ParentDir & sDir
l = l + 1
End If
End If
sDir = Dir
Loop
If l Then
ReDim Preserve asRet(l - 1)
GetDirList = asRet()
End If
End Function
Private Sub AddFiles(ByVal ParentDir As String)
Dim sFile As String
Dim l As Long
If Right(ParentDir, 1) <> "\" Then
ParentDir = ParentDir & "\"
End If
For l = 0 To UBound(m_asFilters)
sFile = Dir(ParentDir & "\" & m_asFilters(l), vbArchive Or vbHidden Or vbNormal Or vbReadOnly Or vbSystem)
Do While Len(sFile)
If Not (sFile = "." Or sFile = "..") Then
If m_lNext >= m_lMax Then
m_lMax = m_lMax + 100
ReDim Preserve m_asFiles(m_lMax)
End If
m_asFiles(m_lNext) = ParentDir & sFile
m_lNext = m_lNext + 1
End If
sFile = Dir
Loop
Next l
End Sub
To quote Valid JavaScript variable names, my write-up summarizing the relevant spec sections:
An identifier must start with
$
,_
, or any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”.The rest of the string can contain the same characters, plus any U+200C zero width non-joiner characters, U+200D zero width joiner characters, and characters in the Unicode categories “Non-spacing mark (Mn)”, “Spacing combining mark (Mc)”, “Decimal digit number (Nd)”, or “Connector punctuation (Pc)”.
I’ve also created a tool that will tell you if any string that you enter is a valid JavaScript variable name according to ECMAScript 5.1 and Unicode 6.1:
P.S. To give you an idea of how wrong Anthony Mills' answer is: if you were to summarize all these rules in a single ASCII-only regular expression for JavaScript, it would be 11,236 characters long. Here it is:
// ES5.1 / Unicode 6.1
/^(?!(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$)[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/
This is a highly inefficient way of doing it. You can use the merge
statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.
MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
UPDATE SET l.studName = s.studName
WHERE l.studName != s.studName
WHEN NOT MATCHED THEN
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)
Make sure you commit
, once completed, in order to be able to see this in the database.
To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.
It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.
However, as I say this will not be as efficient as merge
.
declare
cursor c_data is
select b.rowid as rid, a.studId, a.studName
from student a
left outer join studLoad b
on a.studId = b.studId
and a.studName <> b.studName
;
type t__data is table of c_data%rowtype index by binary_integer;
t_data t__data;
begin
open c_data;
loop
fetch c_data bulk collect into t_data limit 10000;
exit when t_data.count = 0;
for idx in t_data.first .. t_data.last loop
if t_data(idx).rid is null then
insert into studLoad (studId, studName)
values (t_data(idx).studId, t_data(idx).studName);
else
update studLoad
set studName = t_data(idx).studName
where rowid = t_data(idx).rid
;
end if;
end loop;
end loop;
close c_data;
end;
/
<select ng-model="selectedCar" ><option ng-repeat="car in cars " value="{{car.model}}">{{car.model}}</option></select>
<script>var app = angular.module('myApp', []);app.controller('myCtrl', function($scope) { $scope.cars = [{model : "Ford Mustang", color : "red"}, {model : "Fiat 500", color : "white"},{model : "Volvo XC90", color : "black"}];
$scope.selectedCar=$scope.cars[0].model ;});
It wont work since you use URL link with "file://". Instead you should match your directory to your HTML file, for example:
Lets say my file placed in:
C:/myuser/project/file.html
And my wanted image is in:
C:/myuser/project2/image.png
All I have to do is matching the directory this way:
<img src="../project2/image.png" />
in some case you can use annotation @Primary.
@Primary
class USA implements Country {}
This way it will be selected as the default autowire candididate, with no need to autowire-candidate on the other bean.
for mo deatils look at Autowiring two beans implementing same interface - how to set default bean to autowire?
I'll not address the order of tests, sorry. Others already did it. Also, if you know about "ordered tests" - well, this is MS VS's response to the problem. I know that those ordered-tests are no fun. But they thought it will be "it" and there's really nothing more in MSTest about that.
I write about one of your assumptions:
as there is no way to tear down the static class.
Unless your static class represents some process-wide external state external to your code (like ie. the state of an unmanaged native DLL library thats P/Invoked by the rest of your code), your assumption that there is no way
is not true.
If your static class refers to this, then sorry, you are perfectly right, the rest of this anwer is irrelevant. Still, as you didn't say that, I assume your code is "managed".
Think and check the AppDomain
thingy. Rarely it is needed, but this is exactly the case when you'd probably like to use them.
You can create a new AppDomain, and instantiate the test there, and run the test method there. Static data used by managed code will isolated there and upon completion, you will be able to unload the AppDomain and all the data, statics included, will evaporate. Then, next test would initialize another appdomain, and so on.
This will work unless you have external state that you must track. AppDomains only isolate the managed memory. Any native DLL will still be load per-process and their state will be shared by all AppDomains.
Also, creating/tearing down the appdomains will, well, slow down the tests. Also, you may have problems with assembly resolution in the child appdomain, but they are solvable with reasonable amount of reusable code.
Also, you may have small problems with passing test data to - and back from - the child AppDomain. Objects passed will either have to be serializable in some way, or be MarshalByRef
or etc. Talking cross-domain is almost like IPC.
However, take care here, it will be 100% managed talking. If you take some extra care and add a little work to the AppDomain setup, you will be able to even pass delegates and run them in the target domain. Then, instead of making some hairy cross-domain setup, you can wrap your tests with to something like:
void testmethod()
{
TestAppDomainHelper.Run( () =>
{
// your test code
});
}
or even
[IsolatedAppDomain]
void testmethod()
{
// your test code
}
if your test framework supports creating such wrappers/extensions. After some initial research and work, using them is almost trivial.
Fun! There are a few things to tease out here:
$leadID
seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework."
or '
characters. Since you’re already inside both "
and '
, you’ll want to escape whichever you choose. \'
to escape the PHP quotes, or '
to escape the HTML quotes.<a />
elements are commonly used for “hyper”links, and almost always with a href
attribute to indicate their destination, like this: <a href="http://www.google.com">Google homepage</a>
.return false;
to a Javascript event to suppress default behavior.onclick
doesn’t mean anything on its own. That’s because onclick
is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick
we’re talking about! One such object is window
. You could write <a href="javascript:window.onclick = location.reload;">Activate me to reload when anything is clicked</a>
.onclick
can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">
. I bet you had this in mind.=
assignments. The Javascript =
expects something that hasn’t been run yet. You can wrap things in a function
block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload
): <a href="javascript:window.onclick = function () { window.open( ... ) };"> ...
.<a href="http://www.google.com" target="_blank">Google homepage</a>
.Hope those are useful.
Take selected value:
worksheet name = ordls
form control list box name = DEPDB1
selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)
Instead of using group concat()
you can use just concat()
Select concat(Col1, ',', Col2) as Foo_Bar from Table1;
edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.
Using can also use Java 8 stream API and do the same thing in one line.
If you want to print any specific property then use this syntax:
ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> System.out.println(room.getName()));
OR
ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> {
// here room is available
});
if you want to print all the properties of Java object then use this:
ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(System.out::println);
It is simple. take a look at this
https://codepen.io/anon/pen/mepogj?editors=001
basically you want to deal with states of your component so you check the currently active one. you will need to include
getInitialState: function(){}
//and
isActive: function(){}
check out the code on the link
The value of the match
attribute of the <xsl:template>
instruction must be a match pattern.
Match patterns form a subset of the set of all possible XPath expressions. The first, natural, limitation is that a match pattern must select a set of nodes. There are also other limitations. In particular, reverse axes are not allowed in the location steps (but can be specified within the predicates). Also, no variable or parameter references are allowed in XSLT 1.0, but using these is legal in XSLT 2.x.
/
in XPath denotes the root or document node. In XPath 2.0 (and hence XSLT 2.x) this can also be written as document-node()
.
A match pattern can contain the //
abbreviation.
Examples of match patterns:
<xsl:template match="table">
can be applied on any element named table
.
<xsl:template match="x/y">
can be applied on any element named y
whose parent is an element named x
.
<xsl:template match="*">
can be applied to any element.
<xsl:template match="/*">
can be applied only to the top element of an XML document.
<xsl:template match="@*">
can be applied to any attribute.
<xsl:template match="text()">
can be applied to any text node.
<xsl:template match="comment()">
can be applied to any comment node.
<xsl:template match="processing-instruction()">
can be applied to any processing instruction node.
<xsl:template match="node()">
can be applied to any node: element, text, comment or processing instructon.
You can use the split()
function to break input on the basis of line break.
yourString.split("\n")
Everything has many properties and behaviours so take whatever object you want TV, Mobile, Car, Human or anything.
ABSTRACT everything you need and ENCAPSULATE everything you don't need ;)
If you are looking for a recursive version without using the json
module:
def ordereddict_to_dict(value):
for k, v in value.items():
if isinstance(v, dict):
value[k] = ordereddict_to_dict(v)
return dict(value)
$(".overdue").each( function() {
alert("Your book is overdue.");
});
Note that ".addClass()" works because addClass is a function defined on the jQuery object. You can't just plop any old function on the end of a selector and expect it to work.
Also, probably a bad idea to bombard the user with n popups (where n = the number of books overdue).
Perhaps use the size function:
alert( "You have " + $(".overdue").size() + " books overdue." );
Use encodeURI()
in client JS and use URLDecoder.decode()
in server Java side works.
Example:
Javascript:
$.getJSON(
url,
{
"user": encodeURI(JSON.stringify(user))
},
onSuccess
);
Java:
java.net.URLDecoder.decode(params.user, "UTF-8");
You can always use one of the typeOf functions on JavaScript blogs such as Chris West's. Using a definition such as the following for the typeOf()
function would work:
function typeOf(o){return {}.toString.call(o).slice(8,-1)}
This function (which is declared in the global namespace, can be used like this:
alert("onsubmit is a " + typeOf(elem.onsubmit));
If it is a function, "Function" will be returned. If it is a string, "String" will be returned. Other possible values are shown here.
Proper and Cleanest way
After checking the answers below, it seems that they're kind of hacks that rely on editing the login button view to make it more suitable for your need.
Being in the same position, I've succeeded to customize the facebook login button efficiently.
<mehdi.sakout.fancybuttons.FancyButton
android:id="@+id/facebook_login"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
app:fb_radius="2dp"
app:fb_iconPosition="left"
app:fb_fontIconSize="20sp"
app:fb_iconPaddingRight="10dp"
app:fb_textSize="16sp"
app:fb_text="Facebook Connect"
app:fb_textColor="#ffffff"
app:fb_defaultColor="#39579B"
app:fb_focusColor="#6183d2"
app:fb_fontIconResource=""
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
and implement the onClickListener like so
FacebookLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (AccessToken.getCurrentAccessToken() != null){
mLoginManager.logOut();
} else {
mAccessTokenTracker.startTracking();
mLoginManager.logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile"));
}
}
});
You could find the whole source code on: http://medyo.github.io/customize-the-android-facebook-login-on-android
I solved this problem by adding this line in my index.php
:
$app['config']['view.compiled'] = "storage/framework/cache";
You can use Async - Await:
async function axiosTest() {
const response = await axios.get(url);
const data = await response.json();
}
Two possible approaches:
I don't think popen()
is part of the C++ standard (it's part of POSIX from memory), but it's available on every UNIX I've worked with (and you seem to be targeting UNIX since your command is ./some_command
).
On the off-chance that there is no popen()
, you can use system("./some_command >/tmp/some_command.out");
, then use the normal I/O functions to process the output file.