Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
task :invoke_another_task do
# some code
Rake::Task["another:task"].invoke
end
Among the multitudes of answers here, I figured I'd repost the solution that worked for me and met all of the following conditions:
value=""
)code
<select name="market_vertical" ng-model="vc.viewData.market_vertical"
ng-options="opt as (opt | capitalizeFirst) for opt in vc.adminData.regions">
<option ng-selected="true" value="">select a market vertical</option>
</select>
src
original q&a - https://stackoverflow.com/a/32880941/1121919
If your CSS is constructed completely around ex
or em
units, then this might be possible and feasible. You'd just need to declare font-size: 150%
in your style for body
or html
. This should cause every other lengths to scale proportionally. You can't scale images this way, though, unless they get a style too.
But that's a very big if on most sites, anyway.
You want to try String.format("%f", d)
, which will print your double in decimal notation. Don't use BigDecimal
at all.
Regarding the precision issue: You are first storing 47.48
in the double c
, then making a new BigDecimal
from that double
. The loss of precision is in assigning to c
. You could do
BigDecimal b = new BigDecimal("47.48")
to avoid losing any precision.
Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
//These variable are initalized here as they need to be used in more than one methid
private double currentLatitude; //lat of user
private double currentLongitude; //long of user
private double latitudeVillageApartmets= 53.385952001750184;
private double longitudeVillageApartments= -6.599087119102478;
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
/*These methods all have to do with the map and wht happens if the activity is paused etc*/
//contains lat and lon of another marker
private void setUpMap() {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
mMap.addMarker(marker); // adding marker
}
//contains your lat and lon
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("You are here");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
@Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.
Isn't this what default constructors are for?
class MyModel
{
public MyModel()
{
this.ReturnDate = DateTime.Now;
}
public date ReturnDate {get; set;};
}
One way is to use re.sub, that's my preferred way.
import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string
Output:
hey there
Another way is to use re.escape:
import string
import re
my_str = "hey th~!ere"
chars = re.escape(string.punctuation)
print re.sub(r'['+chars+']', '',my_str)
Output:
hey there
Just a small tip about parameters style in python by PEP-8 parameters should be remove_special_chars
and not removeSpecialChars
Also if you want to keep the spaces just change [^a-zA-Z0-9 \n\.]
to [^a-zA-Z0-9\n\.]
I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.
jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
I was then able to use the JObject.Parse(jsonResult) and everything worked.
If you want to use Anaconda in regular cmd on windows you need to add several paths to your Path env variable.
Those paths are (instead of Anaconda3 the folder may be Anaconda2 depending on the Anaconda version on your PC):
\Users\YOUR_USER\Anaconda3
\Users\YOUR_USER\Anaconda3\Library\mingw-w64\bin
\Users\YOUR_USER\Anaconda3\Library\usr\bin
\Users\YOUR_USER\Anaconda3\Library\bin
\Users\YOUR_USER\Anaconda3\Scripts
\Users\YOUR_USER\Anaconda3\bin
You can do that without an I/O redirection:
sed -i 's/$/\n/' filename
You can also use this command to append a newline to a list of files:
find dir -name filepattern | xargs sed -i 's/$/\n/' filename
For echo
, some shells implement it as a shell builtin command. It might not accept the -e
option. If you still want to use echo
, try to find where the echo
binary file is, using which echo
. In most cases, it is located in /bin/echo
, so you can use /bin/echo -e "\n"
to echo a new line.
You can use Enumeration
:
Hashtable<Integer, String> table = ...
Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
Integer key = enumKey.nextElement();
String val = table.get(key);
if(key==0 && val.equals("0"))
table.remove(key);
}
You can try DBVisualizer some features are not free, but you can get an evaluate license...
You can use special characters to make lots of shapes. Examples: http://jsfiddle.net/martlark/jWh2N/2/
<table>_x000D_
<tr>_x000D_
<td>hollow square</td>_x000D_
<td>□</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>solid circle</td>_x000D_
<td>•</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>open circle</td>_x000D_
<td>๐</td>_x000D_
</tr>_x000D_
_x000D_
</table>
_x000D_
Many more can be found here: HTML Special Characters
Not in any conventional sense of the phrase "inside CSS."
For SQL Server 2000:
SELECT su.name,so.name,so.crdate,*
FROM sysobjects so JOIN sysusers su
ON so.uid = su.uid
WHERE xtype='U'
ORDER BY so.name
I'm going to add this here:
sudo python manage.py runserver 80
Go to your phone or computer and enter your computers internal IP (e.g 192.168.0.12
) into the browser.
At this point you should be connected to the Django server.
This should also work without sudo:
python manage.py runserver 0.0.0.0:8000
No. Either use readFile
or readFileSync
(The latter only at startup time).
Or use an existing library like
Alternatively write your config in a js file rather then a json file like
module.exports = {
// json
}
Getting last nth months data retrieve
SELECT * FROM TABLE_NAME
WHERE DATE_COLUMN BETWEEN '&STARTDATE' AND '&ENDDATE';
This should work.
app = angular.module('plunker', [])
app.controller 'MainCtrl', ($scope) ->
$scope.users = ['bob', 'sean', 'rocky', 'john']
$scope.test = ->
console.log $scope.users
HTML:
<input ng-repeat="user in users" ng-model="user" type="text"/>
<input type="button" value="test" ng-click="test()" />
very simple just use getSelectedItem();
eg :
ArrayAdapter<CharSequence> type=ArrayAdapter.createFromResource(this,R.array.admin_typee,android.R.layout.simple_spinner_dropdown_item);
type.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mainType.setAdapter(type);
String group=mainType.getSelectedItem().toString();
the above method returns an string value
in the above the R.array.admin_type
is an string resource file in values
just create an .xml file in values>>strings
npm ci
Alternatively, as of npm cli v6.5.0 you can use the backronym:
npm clean-install
Sources:
https://github.com/npm/cli/releases/tag/v6.5.0 https://github.com/npm/cli/commit/fc1a8d185fc678cdf3784d9df9eef9094e0b2dec
File > Site Manager > Select your site > Transfer Settings > Active
Works for me.
I typically use this approach:
declare @s varchar(50)
set @s = 'TEST TEST'
select REPLACE(REPLACE(REPLACE(@s,' ','[o][c]'),'[c][o]',''),'[o][c]',' ')
One other way:
Move tag in remote repo.(Replace HEAD with any other if needed.)
$ git push --force origin HEAD:refs/tags/v0.0.1.2
Fetch changes back.
$ git fetch --tags
The problem is that super
needs an object
as an ancestor:
>>> class oldstyle:
... def __init__(self): self.os = True
>>> class myclass(oldstyle):
... def __init__(self): super(myclass, self).__init__()
>>> myclass()
TypeError: must be type, not classobj
On closer examination one finds:
>>> type(myclass)
classobj
But:
>>> class newstyle(object): pass
>>> type(newstyle)
type
So the solution to your problem would be to inherit from object as well as from HTMLParser. But make sure object comes last in the classes MRO:
>>> class myclass(oldstyle, object):
... def __init__(self): super(myclass, self).__init__()
>>> myclass().os
True
If your table is very big, you can also process rows by "small packages" (not all at oce) (laravel doc: Eloquent> Chunking Results )
Post::chunk(200, function($posts)
{
foreach ($posts as $post)
{
// process post here.
}
});
not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
The native lib is expected in one of the following locations
/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
and not in
tomcat/lib
The files in tomcat/lib
are all jar
file and are added by tomcat to the classpath
so that they are available to your application.
The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar
, for linux it could be a .so
file, for windows it could be a .dll
file.
Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.
Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.
org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms
EDIT
The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.
If you are troubling with running your servlet then after the run on sever
command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.
It should be something like that
http://localhost:8080/<your-context-name>/<your-servlet-name>
EDIT 2
Try to call your servlet using the following url
http://localhost:8080/com.filecounter/FileCounter
Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF
.
It is better to configure your servlets there using servlet-name
servlet-class
and url-mapping
. It could look like that:
<servlet>
<description></description>
<display-name>File counter - My first servlet</display-name>
<servlet-name>file_counter</servlet-name>
<servlet-class>com.filecounter.FileCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>file_counter</servlet-name>
<url-pattern>/FileFounter</url-pattern>
</servlet-mapping>
In eclipse dynamic web project the default context name is the same as your project name.
http://localhost:8080/<your-context-name>/FileCounter
will work too.
From API 23 onward, getResources().getColor()
is deprecated.
Use this instead:
textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.color_black));
I felt like replying as well, explaining the same thing as the others a bit differently. I am sure you know most of this, but it might help someone else.
<a href="#" class="view">
The
href="#"
part is a commonly used way to make sure the link doesn't lead anywhere on it's own. the #-attribute is used to create a link to some other section in the same document. For example clicking a link of this kind:
<a href="#news">Go to news</a>
will take you to wherever you have the
<a name="news"></a>
code. So if you specify # without any name like in your case, the link leads nowhere.
The
class="view"
part gives it an identifier that CSS or javascript can use. Inside the CSS-files (if you have any) you will find specific styling procedures on all the elements tagged with the "view"-class.
To find out where the URL is specified I would look in the javascript code. It is either written directly in the same document or included from another file.
Search your source code for something like:
<script type="text/javascript"> bla bla bla </script>
or
<script> bla bla bla </script>
and then search for any reference to your "view"-class. An included javascript file can look something like this:
<script type="text/javascript" src="include/javascript.js"></script>
In that case, open javascript.js under the "include" folder and search in that file. Most commonly the includes are placed between <head>
and </head>
or close to the </body>
-tag.
A faster way to find the link is to search for the actual link it goes to. For example, if you are directed to http://www.google.com/search?q=html when you click it, search for "google.com" or something in all the files you have in your web project, just remember the included files.
In many text editors you can open all the files at once, and then search in them all for something.
Without sharex=True, sharey=True
you get:
With it you should get it nicer:
fig, axes2d = plt.subplots(nrows=3, ncols=3,
sharex=True, sharey=True,
figsize=(6,6))
for i, row in enumerate(axes2d):
for j, cell in enumerate(row):
cell.imshow(np.random.rand(32,32))
plt.tight_layout()
But if you want to add additional labels, you should add them only to the edge plots:
fig, axes2d = plt.subplots(nrows=3, ncols=3,
sharex=True, sharey=True,
figsize=(6,6))
for i, row in enumerate(axes2d):
for j, cell in enumerate(row):
cell.imshow(np.random.rand(32,32))
if i == len(axes2d) - 1:
cell.set_xlabel("noise column: {0:d}".format(j + 1))
if j == 0:
cell.set_ylabel("noise row: {0:d}".format(i + 1))
plt.tight_layout()
Adding label for each plot would spoil it (maybe there is a way to automatically detect repeated labels, but I am not aware of one).
Sometimes the command that cron needs to run is in a directory where cron has no access, typically on systems where users' home directories' permissions are 700 and the command is in that directory.
As listed in other answers, the trick (in SQL 2005 or later) is to change the global configuration settings for show advanced options
and xp_cmdshell
to 1
, in that order.
Adding to this, if you want to preserve the previous values, you can read them from sys.configurations
first, then apply them in reverse order at the end. We can also avoid unnecessary reconfigure
calls:
declare @prevAdvancedOptions int
declare @prevXpCmdshell int
select @prevAdvancedOptions = cast(value_in_use as int) from sys.configurations where name = 'show advanced options'
select @prevXpCmdshell = cast(value_in_use as int) from sys.configurations where name = 'xp_cmdshell'
if (@prevAdvancedOptions = 0)
begin
exec sp_configure 'show advanced options', 1
reconfigure
end
if (@prevXpCmdshell = 0)
begin
exec sp_configure 'xp_cmdshell', 1
reconfigure
end
/* do work */
if (@prevXpCmdshell = 0)
begin
exec sp_configure 'xp_cmdshell', 0
reconfigure
end
if (@prevAdvancedOptions = 0)
begin
exec sp_configure 'show advanced options', 0
reconfigure
end
Note that this relies on SQL Server version 2005 or later (original question was for 2008).
Call Enum.GetValues
; this returns an array that represents all possible values for your enum. Pick a random item from this array. Cast that item back to the original enum type.
You should include "bPaginate": false,
into the configuration object you pass to your constructor parameters. As seen here: http://datatables.net/release-datatables/examples/basic_init/filter_only.html
Most modern regex implementations allow for recursive regexpressions, which can verify a complete JSON serialized structure. The json.org specification makes it quite straightforward.
$pcre_regex = '
/
(?(DEFINE)
(?<number> -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
(?<boolean> true | false | null )
(?<string> " ([^"\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
(?<array> \[ (?: (?&json) (?: , (?&json) )* )? \s* \] )
(?<pair> \s* (?&string) \s* : (?&json) )
(?<object> \{ (?: (?&pair) (?: , (?&pair) )* )? \s* \} )
(?<json> \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
)
\A (?&json) \Z
/six
';
It works quite well in PHP with the PCRE functions . Should work unmodified in Perl; and can certainly be adapted for other languages. Also it succeeds with the JSON test cases.
A simpler approach is the minimal consistency check as specified in RFC4627, section 6. It's however just intended as security test and basic non-validity precaution:
var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + text + ')');
If you want to clear all item you stored in localStorage then
localStorage.clear();
Use this for clear all stored key.
If you want to clear/remove only specific key/value then you can use removeItem(key).
localStorage.removeItem('yourKey');
Based on previous answers (but fixed)
using static System.IO.Path;
var dir = GetFileName(path?.TrimEnd(DirectorySeparatorChar, AltDirectorySeparatorChar));
Explanation of GetFileName
from .NET source:
Returns the name and extension parts of the given path. The resulting string contains the characters of path that follow the last backslash ("\"), slash ("/"), or colon (":") character in path. The resulting string is the entire path if path contains no backslash after removing trailing slashes, slash, or colon characters. The resulting string is null if path is null.
I was getting this env: node: No such file or directory
error when running the job through Jenkins.
What I did to fix it - added export PATH="$PATH:"/usr/local/bin/
at the beginning of the script that Jenkins job executes.
Example
public static string JsonFormatter(string json)
{
StringBuilder builder = new StringBuilder();
bool quotes = false;
bool ignore = false;
int offset = 0;
int position = 0;
if (string.IsNullOrEmpty(json))
{
return string.Empty;
}
json = json.Replace(Environment.NewLine, "").Replace("\t", "");
foreach (char character in json)
{
switch (character)
{
case '"':
if (!ignore)
{
quotes = !quotes;
}
break;
case '\'':
if (quotes)
{
ignore = !ignore;
}
break;
}
if (quotes)
{
builder.Append(character);
}
else
{
switch (character)
{
case '{':
case '[':
builder.Append(character);
builder.Append(Environment.NewLine);
builder.Append(new string(' ', ++offset * 4));
break;
case '}':
case ']':
builder.Append(Environment.NewLine);
builder.Append(new string(' ', --offset * 4));
builder.Append(character);
break;
case ',':
builder.Append(character);
builder.Append(Environment.NewLine);
builder.Append(new string(' ', offset * 4));
break;
case ':':
builder.Append(character);
builder.Append(' ');
break;
default:
if (character != ' ')
{
builder.Append(character);
}
break;
}
position++;
}
}
return builder.ToString().Trim();
}
I was able to solve this using local_action to scp to file from machineA to machineC and then copying the file to machineB.
It usually happens when Allow Nulls option is unchecked.
Solution:
Try these steps. It worked for me.
Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"
Short version:
$ svn st
! + C foo
> local edit, incoming delete upon update
! + C bar
> local edit, incoming delete upon update
$ touch foo bar
$ svn revert foo bar
$ rm foo bar
If the conflict is about directories instead of files then replace touch
with mkdir
and rm
with rm -r
.
Note: the same procedure also work for the following situation:
$ svn st
! C foo
> local delete, incoming delete upon update
! C bar
> local delete, incoming delete upon update
Long version:
This happens when you edit a file while someone else deleted the file and commited first. As a good svn citizen you do an update before a commit. Now you have a conflict. Realising that deleting the file is the right thing to do you delete the file from your working copy. Instead of being content svn now complains that the local files are missing and that there is a conflicting update which ultimately wants to see the files deleted. Good job svn.
Should svn resolve
not work, for whatever reason, you can do the following:
Initial situation: Local files are missing, update is conflicting.
$ svn st
! + C foo
> local edit, incoming delete upon update
! + C bar
> local edit, incoming delete upon update
Recreate the conflicting files:
$ touch foo bar
If the conflict is about directories then replace touch
with mkdir
.
New situation: Local files to be added to the repository (yeah right, svn, whatever you say), update still conflicting.
$ svn st
A + C foo
> local edit, incoming delete upon update
A + C bar
> local edit, incoming delete upon update
Revert the files to the state svn likes them (that means deleted):
$ svn revert foo bar
New situation: Local files not known to svn, update no longer conflicting.
$ svn st
? foo
? bar
Now we can delete the files:
$ rm foo bar
If the conflict is about directories then replace rm
with rm -r
.
svn no longer complains:
$ svn st
Done.
Worked For me
object item = dgwLoadItems.SelectedItem;
string ID = (dgwLoadItems.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
MessageBox.Show(ID);
function setSelectedIndex(s, v) {
for ( var i = 0; i < s.options.length; i++ ) {
if ( s.options[i].value == v ) {
s.options[i].selected = true;
return;
}
}
}
Where s is the dropdown and v is the value
Given that IPV6 has a size of 1500, I would assert that carriers would not provide separate paths for IPV4 and IPV6 (they are both IP with different types), forcing them to equipment for ipv4 that would be old, redundant, more costly to maintain and less reliable. It wouldn't make any sense. Besides, doing so might easily be considered providing preferential treatment for some traffic -- a no no under rules they probably don't care much about (unless they get caught).
So 1472 should be safe for external use (though that doesn't mean an app like DNS that doesn't know about EDNS will accept it), and if you are talking internal nets, you can more likely know your network layout in which case jumbo packet sizes apply for for non-fragmented packets so for 4096 - 4068 bytes, and for intel's cards with 9014 byte buffers, a package size of ... wait...8086 bytes, would be the max...coincidence? snicker
****UPDATE****
Various answers give maximum values allowed by 1 SW vendor or various answers assuming encapsulation. The user didn't ask for the lowest value possible (like "0" for a safe UDP size), but the largest safe packet size.
Encapsulation values for various layers can be included multiple times. Since once you've encapsulated a stream -- there is nothing prohibiting, say, a VPN layer below that and a complete duplication of encapsulation layers above that.
Since the question was about maximum safe values, I'm assuming that they are talking about the maximum safe value for a UDP packet that can be received. Since no UDP packet is guaranteed, if you receive a UDP packet, the largest safe size would be 1 packet over IPv4 or 1472 bytes.
Note -- if you are using IPv6, the maximum size would be 1452 bytes, as IPv6's header size is 40 bytes vs. IPv4's 20 byte size (and either way, one must still allow 8 bytes for the UDP header).
{{game.gameDate | date('c')}} // 2014-02-05T16:45:22+00:00
For full date time string including timezone offset.
cv::Mat m;
m.create(10, 10, CV_32FC3);
float *array = (float *)malloc( 3*sizeof(float)*10*10 );
cv::MatConstIterator_<cv::Vec3f> it = m.begin<cv::Vec3f>();
for (unsigned i = 0; it != m.end<cv::Vec3f>(); it++ ) {
for ( unsigned j = 0; j < 3; j++ ) {
*(array + i ) = (*it)[j];
i++;
}
}
Now you have a float array. In case of 8 bit, simply change float
to uchar
, Vec3f
to Vec3b
and CV_32FC3
to CV_8UC3
.
When I upgraded my website PHP from version 5.6 to 7.2, I encountered this problem “Your PHP installation appears to be missing the MySQL extension which is required by WordPress”. It turns out that mysql extension is no longer supported in PHP version 7.2. It is now using mysqli extention. I am using old version of WordPress which still using mysql extension that is why the problem existed. So what I did is upgraded the WordPress to the core. This solve the problem.
Here's the steps I followed when upgrading WordPress manually.
You could use the between function to get all records between 2010-08-03 00:00:00:000 AND 2010-08-03 23:59:59:000
Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host
. What Out-Host
does is obviously host-dependent.
Just letting things fall out of the pipeline is not a substitute for Write-Host
which exists for the sole reason of outputting text in the host application.
If you want output, then use the Write-*
cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.
This one helped me for DataTables Version 1.10.4, because its new API
var oTable = $('#myTable').DataTable();
$('#myInputTextField').keyup(function(){
oTable.search( $(this).val() ).draw();
})
Use the retainAll()
method of Set
:
Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets
If you want to preserve the sets, create a new set to hold the intersection:
Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);
The javadoc of retainAll()
says it's exactly what you want:
Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.
I prefer the second way.
When you use the first way, if you decide to use a parallel stream to improve performance, you'll have no control over the order in which the elements will be added to the output list by forEach
.
When you use toList
, the Streams API will preserve the order even if you use a parallel stream.
i have found and easier solution to handle threads when orientation change. You can just keep an static reference to your activity/fragment and verify if its null before acting on the ui. I suggest using a try catch too:
public class DashListFragment extends Fragment {
private static DashListFragment ACTIVE_INSTANCE;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ACTIVE_INSTANCE = this;
new Handler().postDelayed(new Runnable() {
public void run() {
try {
if (ACTIVE_INSTANCE != null) {
setAdapter(); // this method do something on ui or use context
}
}
catch (Exception e) {}
}
}, 1500l);
}
@Override
public void onDestroy() {
super.onDestroy();
ACTIVE_INSTANCE = null;
}
}
For this install, I was using KUbuntu 13.04, 64bit.
The first step is to download the latest version (assuming versions in the future work in a similar way) from www.glfw.org, probably using this link.
The next step is to extract the archive, and open a terminal. cd
into the glfw-3.X.X directory and run cmake -G "Unix Makefiles"
you may need elevated privileges, and you may also need to install build dependencies first. To do this, try sudo apt-get build-dep glfw
or sudo apt-get build-dep glfw3
or do it manually, as I did using sudo apt-get install cmake xorg-dev libglu1-mesa-dev
... There may be other libs you require such as the pthread libraries... Apparently I had them already. (See the -l options given to the g++ linker stage, below.)
Now you can type make
and then make install
, which will probably require you to sudo
first.
Okay, you should get some verbose output on the last three CMake stages, telling you what has been built or where it has been placed. (In /usr/include
, for example.)
The next step is to fire up vim ("what?! vim?!" you say) or your preferred IDE / text editor... I didn't use vim, I used Kate, because I am on KUbuntu 13.04... Anyway, download or copy the test program from here (at the bottom of the page) and save, exit.
Now compile using g++ -std=c++11 -c main.cpp
- not sure if c++11 is required but I used nullptr
so, I needed it... You may need to upgrade your gcc to version 4.7, or the upcoming version 4.8... Info on that here.
Then fix your errors if you typed the program by hand or tried to be "too clever" and something didn't work... Then link it using this monster! g++ main.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi
So you see, in the "install build dependencies" part, you may also want to check you have the GL, GLU, X11 Xxf86vm (whatever that is) Xrandr posix-thread and Xi (whatever that is) development libraries installed also. Maybe update your graphics drivers too, I think GLFW 3 may require OpenGL version 3 or higher? Perhaps someone can confirm that? You may also need to add the linker options -ldl -lXinerama -lXcursor
to get it to work correctly if you are getting undefined references to dlclose
(credit to @user2255242).
And, yes, I really did need that many -l
s!
Hopefully this information was correct and everything worked for you, and you enjoyed writing the GLFW test program. Also hopefully this guide has helped, or will help, a few people in the future who were struggling as I was today yesterday!
By the way, all the tags are the things I searched for on stackoverflow looking for an answer that didn't exist. (Until now.) Hopefully they are what you searched for if you were in a similar position to myself.
This might not be a good idea. This method (using sudo make install) might be harzardous to your system. (See Don't Break Debian)
Ideally I, or someone else, should propose a solution which does not just install lib files etc into the system default directories as these should be managed by package managers such as apt
, and doing so may cause a conflict and break your package management system.
See the new "2020 answer" for an alternative solution.
Turns out that EVERY part of an NSAttributedString must have a dictionary set with at least NSFontAttributeName and NSForegroundColorAttributeName set, if you wish boundingRectWithSize to actually work!
I don't see that documented anywhere.
This tested snippet should do it:
import re
line = re.sub(r"</?\[\d+>", "", line)
Edit: Here's a commented version explaining how it works:
line = re.sub(r"""
(?x) # Use free-spacing mode.
< # Match a literal '<'
/? # Optionally match a '/'
\[ # Match a literal '['
\d+ # Match one or more digits
> # Match a literal '>'
""", "", line)
Regexes are fun! But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special: "metacharacters" which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: www.regular-expressions.info. The time you spend there will pay for itself many times over. Happy regexing!
You are likely using the wrong username to login:
ubuntu
ec2-user
root
or admin
To login, you need to adjust your ssh command:
ssh -l USERNAME_HERE -i .ssh/yourkey.pem public-ec2-host
HTH
Here is a Swift 3 compatible answer, that will also work with view controllers within a navigation controller - as they will change the scroll views contentInset.top
property.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.registerKeyboardNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.unregisterKeyboardNotifications()
}
func registerKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardDidShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func unregisterKeyboardNotifications() {
NotificationCenter.default.removeObserver(self)
}
func keyboardDidShow(notification: NSNotification) {
let userInfo: NSDictionary = notification.userInfo! as NSDictionary
let keyboardInfo = userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue
let keyboardSize = keyboardInfo.cgRectValue.size
// Get the existing contentInset for the scrollView and set the bottom property to be the height of the keyboard
var contentInset = self.scrollView.contentInset
contentInset.bottom = keyboardSize.height
self.scrollView.contentInset = contentInset
self.scrollView.scrollIndicatorInsets = contentInset
}
func keyboardWillHide(notification: NSNotification) {
var contentInset = self.scrollView.contentInset
contentInset.bottom = 0
self.scrollView.contentInset = contentInset
self.scrollView.scrollIndicatorInsets = UIEdgeInsets.zero
}
You need to set the OFS
variable (output field separator) to be a tab:
echo "$line" |
awk -v var="$mycol_new" -F $'\t' 'BEGIN {OFS = FS} {$3 = var; print}'
(make sure you quote the $line
variable in the echo statement)
System apps installed /system/app/ or /system/priv-app. Other apps can be installed in /data/app or /data/preload/.
Connect to your android mobile with USB and run the following commands. You will see all the installed packages.
$ adb shell
$ pm list packages -f
Join like this:
ON a.userid = b.sourceid AND a.listid = b.destinationid;
Looking at the various responses above, and drawing on my own recent experience (I got this error code doing something completely unrelated -- setting Application.Calculation
) I conclude that the same error code is used to indicate multiple unrelated problems. So @Garreh you should probably be asking a new question (not that anyone will be able to help based on the error code alone). I've seen the same thing working with Word interop from C#, where the same HRESULT
seems to be used for almost every kind of error. I've never found any satisfactory Microsoft documentation on what the codes might mean.
Here is the working solution
create a new page main.html
example:
<!doctype html>
<html>
<head>
<title>tittle</title>
<script>
window.location='./index.html';
</script>
</head>
<body>
</body>
</html>
change the following in mainactivity.java
super.loadUrl("file:///android_asset/www/index.html");
to
super.loadUrl("file:///android_asset/www/main.html");
Now build your application and it works on any slow connection
NOTE: This is a workaround I found in 2013.
Here one big collection of debug constants that we use. Enjoy.
// Uncomment the defitions to show additional info.
// #define DEBUG
// #define DEBUGWHERE_SHOWFULLINFO
// #define DEBUG_SHOWLINES
// #define DEBUG_SHOWFULLPATH
// #define DEBUG_SHOWSEPARATORS
// #define DEBUG_SHOWFULLINFO
// Definition of DEBUG functions. Only work if DEBUG is defined.
#ifdef DEBUG
#define debug_separator() NSLog( @"----------------------------------------------------------------------------" );
#ifdef DEBUG_SHOWSEPARATORS
#define debug_showSeparators() debug_separator();
#else
#define debug_showSeparators()
#endif
/// /// /// ////// /////
#ifdef DEBUG_SHOWFULLPATH
#define debug_whereFull() debug_showSeparators(); NSLog(@"Line:%d : %s : %s", __LINE__,__FILE__,__FUNCTION__); debug_showSeparators();
#else
#define debug_whereFull() debug_showSeparators(); NSLog(@"Line:%d : %s : %s", __LINE__,[ [ [ [NSString alloc] initWithBytes:__FILE__ length:strlen(__FILE__) encoding:NSUTF8StringEncoding] lastPathComponent] UTF8String ] ,__FUNCTION__); debug_showSeparators();
#endif
/// /// /// ////// /////
#define debugExt(args,...) debug_separator(); debug_whereFull(); NSLog( args, ##__VA_ARGS__); debug_separator();
/// /// /// ////// ///// Debug Print Macros
#ifdef DEBUG_SHOWFULLINFO
#define debug(args,...) debugExt(args, ##__VA_ARGS__);
#else
#ifdef DEBUG_SHOWLINES
#define debug(args,...) debug_showSeparators(); NSLog([ NSString stringWithFormat:@"Line:%d : %@", __LINE__, args ], ##__VA_ARGS__); debug_showSeparators();
#else
#define debug(args,...) debug_showSeparators(); NSLog(args, ##__VA_ARGS__); debug_showSeparators();
#endif
#endif
/// /// /// ////// ///// Debug Specific Types
#define debug_object( arg ) debug( @"Object: %@", arg );
#define debug_int( arg ) debug( @"integer: %i", arg );
#define debug_float( arg ) debug( @"float: %f", arg );
#define debug_rect( arg ) debug( @"CGRect ( %f, %f, %f, %f)", arg.origin.x, arg.origin.y, arg.size.width, arg.size.height );
#define debug_point( arg ) debug( @"CGPoint ( %f, %f )", arg.x, arg.y );
#define debug_bool( arg ) debug( @"Boolean: %@", ( arg == YES ? @"YES" : @"NO" ) );
/// /// /// ////// ///// Debug Where Macros
#ifdef DEBUGWHERE_SHOWFULLINFO
#define debug_where() debug_whereFull();
#else
#define debug_where() debug(@"%s",__FUNCTION__);
#endif
#define debug_where_separators() debug_separator(); debug_where(); debug_separator();
/// /// /// ////// /////
#else
#define debug(args,...)
#define debug_separator()
#define debug_where()
#define debug_where_separators()
#define debug_whereFull()
#define debugExt(args,...)
#define debug_object( arg )
#define debug_int( arg )
#define debug_rect( arg )
#define debug_bool( arg )
#define debug_point( arg )
#define debug_float( arg )
#endif
Batch files have really very limited logic powers so the best you can hope to come up with is a good workaround that indirectly achieves what you want. That's not to say that you should feel they are inferior to a real language - they still demand the same attention to detail and manual debugging as a real application. It's just that you'll need to work a lot harder to make them do what you want in a robust manner.
For the OP's question it sounds like you require two specific files to exist. Just use a tally:
IF EXIST somefile.txt (
set /a file1_status=1
)
IF EXIST someotehrfile.txt (
set /a file2_status=1
)
set /a file_status_result=file1_status + file2_status
if %file_status_result% equ 2 (
goto somefileexists
)
goto exit
:somefileexists
IF EXIST someotherfile.txt SET var=...
:exit
My example uses 3 variables, but you could just add 1 to file_result_status if the file exists. But if you want more granular control later in your batch file you can record the result for each file as I have done so you don't have to keep checking if a file exists later on.
You can use COLLATE NOCASE
in your SELECT
query:
SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE
Additionaly, in SQLite, you can indicate that a column should be case insensitive when you create the table by specifying collate nocase
in the column definition (the other options are binary
(the default) and rtrim
; see here). You can specify collate nocase
when you create an index as well. For example:
create table Test ( Text_Value text collate nocase ); insert into Test values ('A'); insert into Test values ('b'); insert into Test values ('C'); create index Test_Text_Value_Index on Test (Text_Value collate nocase);
Expressions involving Test.Text_Value
should now be case insensitive. For example:
sqlite> select Text_Value from Test where Text_Value = 'B'; Text_Value ---------------- b sqlite> select Text_Value from Test order by Text_Value; Text_Value ---------------- A b C sqlite> select Text_Value from Test order by Text_Value desc; Text_Value ---------------- C b A
The optimiser can also potentially make use of the index for case-insensitive searching and matching on the column. You can check this using the explain
SQL command, e.g.:
sqlite> explain select Text_Value from Test where Text_Value = 'b'; addr opcode p1 p2 p3 ---------------- -------------- ---------- ---------- --------------------------------- 0 Goto 0 16 1 Integer 0 0 2 OpenRead 1 3 keyinfo(1,NOCASE) 3 SetNumColumns 1 2 4 String8 0 0 b 5 IsNull -1 14 6 MakeRecord 1 0 a 7 MemStore 0 0 8 MoveGe 1 14 9 MemLoad 0 0 10 IdxGE 1 14 + 11 Column 1 0 12 Callback 1 0 13 Next 1 9 14 Close 1 0 15 Halt 0 0 16 Transaction 0 0 17 VerifyCookie 0 4 18 Goto 0 1 19 Noop 0 0
use the helper function in laravel 5.1 instead:
return response()->json(['name' => 'Abigail', 'state' => 'CA']);
This will create an instance of \Illuminate\Routing\ResponseFactory
. See the phpDocs for possible parameters below:
/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response
* @static
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){
return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}
Most of what I write has already been covered by Pressacco, but this is specific to SpecFlow.
I was getting this message for the <specFlow>
element and therefore I added a specflow.xsd
file to the solution this answer (with some modifications to allow for the <plugins>
element).
Thereafter I (like Pressacco), right clicked within the file buffer of app.config
and selected properties, and within Schemas
, I added "specflow.xsd"
to the end. The entirety of Schemas
now reads:
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\1033\DotNetConfig.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\EntityFrameworkConfig_6_1_0.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\RazorCustomSchema.xsd" "specflow.xsd"
Simple change to syntax is all that is needed:
create table ImagenesUsuario (
idImagen int not null identity(1,1) primary key
)
By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:
create table ImagenesUsuario (
idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
)
Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).
Try to this cors npm modules.
var cors = require('cors')
var app = express()
app.use(cors())
This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
Arhhh this got me and I spent a lot of time troubleshooting it. The problem was my tests were being executed in Parellel (the default with XUnit).
To make my test run sequentially I decorated each class with this attribute:
[Collection("Sequential")]
This is how I worked it out: Execute unit tests serially (rather than in parallel)
I mock up my EF In Memory context with GenFu:
private void CreateTestData(TheContext dbContext)
{
GenFu.GenFu.Configure<Employee>()
.Fill(q => q.EmployeeId, 3);
var employee = GenFu.GenFu.ListOf<Employee>(1);
var id = 1;
GenFu.GenFu.Configure<Team>()
.Fill(p => p.TeamId, () => id++).Fill(q => q.CreatedById, 3).Fill(q => q.ModifiedById, 3);
var Teams = GenFu.GenFu.ListOf<Team>(20);
dbContext.Team.AddRange(Teams);
dbContext.SaveChanges();
}
When Creating Test Data, from what I can deduct, it was alive in two scopes (once in the Employee's Tests while the Team tests were running):
public void Team_Index_should_return_valid_model()
{
using (var context = new TheContext(CreateNewContextOptions()))
{
//Arrange
CreateTestData(context);
var controller = new TeamController(context);
//Act
var actionResult = controller.Index();
//Assert
Assert.NotNull(actionResult);
Assert.True(actionResult.Result is ViewResult);
var model = ModelFromActionResult<List<Team>>((ActionResult)actionResult.Result);
Assert.Equal(20, model.Count);
}
}
Wrapping both Test Classes with this sequential collection attribute has cleared the apparent conflict.
[Collection("Sequential")]
Additional references:
https://github.com/aspnet/EntityFrameworkCore/issues/7340
EF Core 2.1 In memory DB not updating records
http://www.jerriepelser.com/blog/unit-testing-aspnet5-entityframework7-inmemory-database/
http://gunnarpeipman.com/2017/04/aspnet-core-ef-inmemory/
https://github.com/aspnet/EntityFrameworkCore/issues/12459
Preventing tracking issues when using EF Core SqlLite in Unit Tests
In Addition to the suggestions, I would also suggest annotating your Repository interface with @Repository.
The Spring IOC may not detect this as a repository and thus be unable to detect the entity and its corresponding property.
Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).
Instead, I used this method:
Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
In order to calculate the difference you have to put the +
operator,
that way typescript
converts the dates to numbers.
+new Date()- +new Date("2013-02-20T12:01:04.753Z")
From there you can make a formula to convert the difference to minutes
or hours
.
You can use upstream headers (named starting with $http_) and additional custom headers. For example:
add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01 txt01;
next, go to console and make request with user's header:
curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/
the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:
HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1
I am thinking this may not be possible in Java because annotation and its parameters are resolved at compile time.
With Seam 2 http://seamframework.org/ you were able to resolve annotation parameters at runtime, with expression language inside double quotes.
In Seam 3 http://seamframework.org/Seam3/Solder, this feature is the module Seam Solder
Here is some methods I've been used in the past to trim strings in js:
String.prototype.ltrim = function( chars ) {
chars = chars || "\\s*";
return this.replace( new RegExp("^[" + chars + "]+", "g"), "" );
}
String.prototype.rtrim = function( chars ) {
chars = chars || "\\s*";
return this.replace( new RegExp("[" + chars + "]+$", "g"), "" );
}
String.prototype.trim = function( chars ) {
return this.rtrim(chars).ltrim(chars);
}
TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)
The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.
"name":"value"
.Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.
What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name")
, and then create another JProperty of your desire and then add it after this using AddAfterSelf
method. You are done then.
For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm
This is the code I modified.
public class Program
{
public static void Main()
{
try
{
string jsonText = @"
{
""food"": {
""fruit"": {
""apple"": {
""colour"": ""red"",
""size"": ""small""
},
""orange"": {
""colour"": ""orange"",
""size"": ""large""
}
}
}
}";
var foodJsonObj = JObject.Parse(jsonText);
var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");
var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));
Console.WriteLine(foodJsonObj.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
}
}
}
You're not using splice correctly:
arr.splice(4, 1)
this will remove 1 item at index 4. see here
I think you want to use slice:
arr.slice(0,5)
this will return elements in position 0 through 4.
This assumes all the rest of your code (cookies etc) works correctly
When I used the Scaffold-DbContext command, it didn't include the "[key]" annotation in the model files or the "entity.HasKey(..)" entry in the "modelBuilder.Entity" blocks. My solution was to add a line like this in every "modelBuilder.Entity" block in the *Context.cs file:
entity.HasKey(X => x.Id);
I'm not saying this is better, or even the right way. I'm just saying that it worked for me.
As mentioned here, this feature is not currently supported.
The solutions provided by others used to work for me but is not working for me anymore, which is as below.
brew services stop mongodb
brew services start mongodb
brew services list
gives
Name Status User Plist
mongodb-community started XXXXXXXXX /Users/XXXXXXXXX/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
So I used mongodb-community
instead of mongodb
which worked for me
brew services stop mongodb-community
brew services start mongodb-community
Since sudo will not work with redirection >
, I like the tee
command for this purpose
echo "" | sudo tee fileName
For anybody using logging.config.dictConfig
you can alter the requests library log level in the dictionary like this:
'loggers': {
'': {
'handlers': ['file'],
'level': level,
'propagate': False
},
'requests.packages.urllib3': {
'handlers': ['file'],
'level': logging.WARNING
}
}
ID's must be unique (only be given to one element in the DOM at a time), whereas classes don't have to be. You've already discovered the CSS .
class and #
ID prefixes, so that's pretty much it.
From the documentation:
$this->db->insert_id()
The insert ID number when performing database inserts.
Therefore, you could use something like this:
$lastid = $this->db->insert_id();
That's a specific case of the rule that you shouldn't catch any exception you don't know how to handle. If you don't know how to handle it, it's always better to let some other part of the system catch and handle it.
If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$tag = 'YOUR_TAG_HERE';
$client_id = "YOUR_CLIENT_ID";
$url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
//Now parse through the $results array to display your results...
foreach($results['data'] as $item){
$image_link = $item['images']['low_resolution']['url'];
echo '<img src="'.$image_link.'" />';
}
Here's another good solution on stackblitz.
Alternatively:
The accepted answer is a good solution, but it can be improved since your content/chat may often scroll to the bottom involuntarily given how the ngAfterViewChecked() lifecycle hook works.
Here's an improved version...
COMPONENT
import {..., AfterViewChecked, ElementRef, ViewChild, OnInit} from 'angular2/core'
@Component({
...
})
export class ChannelComponent implements OnInit, AfterViewChecked {
@ViewChild('scrollMe') private myScrollContainer: ElementRef;
/**Add the variable**/
scrolledToBottom = false;
ngAfterViewChecked() {
this.scrollToBottom();
}
scrollToBottom(): void {
try {
/**Add the condition**/
if(!this.scrolledToBottom){
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
}
} catch(err) { }
}
/**Add the method**/
onScroll(){
this.scrolledToBottom = true;
}
}
TEMPLATE
<!--Add a scroll event listener-->
<div #scrollMe
style="overflow: scroll; height: xyz;"
(scroll)="onScroll()">
<div class="..."
*ngFor="..."
...>
</div>
</div>
The solution for Windows
is to clone the repository to other folder and then copy and paste to the original location or just copy the .git
invisible folder.
If you need to check option selected state for specific value:
$('#selectorId option[value=YOUR_VALUE]:selected')
Update for RxJS 6 (April 2018)
It is now perfectly fine to import directly from rxjs
. (As can be seen in Angular 6+). Importing from rxjs/operators
is also fine and it is actually no longer possible to import operators globally (one of major reasons for refactoring rxjs 6
and the new approach using pipe
). Thanks to this treeshaking can now be used as well.
Sample code from rxjs repo:
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
range(1, 200)
.pipe(filter(x => x % 2 === 1), map(x => x + x))
.subscribe(x => console.log(x));
Backwards compatibility for rxjs < 6?
rxjs team released a compatibility package on npm that is pretty much install & play. With this all your rxjs 5.x
code should run without any issues. This is especially useful now when most of the dependencies (i.e. modules for Angular) are not yet updated.
Checking out more than one repo at a time in a single workspace is not possible with Jenkins + Git Plugin.
As a workaround, you can either have multiple upstream jobs which checkout a single repo each and then copy to your final project workspace (Problematic on a number of levels), or you can set up a shell scripting step which checks out each needed repo to the job workspace at build time.
Previously the Multiple SCM plugin could help with this issue but it is now deprecated. From the Multiple SCM plugin page: "Users should migrate to https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin . Pipeline offers a better way of checking out of multiple SCMs, and is supported by the Jenkins core development team."
click link get example file upload clint java with apache HttpComponents
and library downalod link
https://hc.apache.org/downloads.cgi
use 4.5.3.zip it's working fine in my code
and my working code..
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");
FileBody bin = new FileBody(new File("E:\\meter.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
$post = Post::select(DB::raw('count(*) as user_count, category_id'))
->groupBy('category_id')
->get();
This is an example which results count of post by category.
I Also come across these kind of requirements recently.I set the below properties with out writing the code it works.see if this helps you.
It's pretty hard to say definitively without seeing what the rendered html looks like and what styles are being applied to the elements within the treeview div, but the thing that jumps out at me right away is the
overflow-x: scroll;
What happens if you remove that?
what about changing the position: relative on your #content #text div to position: absolute
#content #text {
position:absolute;
width:950px;
height:215px;
color:red;
}
then you can use the css properties left and top to position within the #content div
The os.exec*()
functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system()
.
I faced same issue on my wordpress site. After the lot of debugging i fixed my problem step by step like this.
define('SCRIPT_DEBUG', TRUE); define('WP_DEBUG', TRUE); define( 'WP_DEBUG_LOG', true );
deferred.jqXHR = $.ajax( options ).done( function( response ) { try { response = JSON.parse(response); } catch (Exception) { response = response; }
Please check your may be resolved.
define('SCRIPT_DEBUG', TRUE); define('WP_DEBUG', TRUE); define( 'WP_DEBUG_LOG', true );
*change your own risk if your update your wordpress version your changed may be lost.
Here's an example:
public class Main {
public static void main(String[] args) {
double val1 = 100;
double val2 = 10;
char operation = 'd';
double result = 0;
switch (operation) {
case 'a':
result = val1 + val2; break;
case 's':
result = val1 - val2; break;
case 'd':
if (val2 != 0)
result = val1 / val2; break;
case 'm':
result = val1 * val2; break;
default: System.out.println("Not a defined operation");
}
System.out.println(result);
}
}
I prefer this method as it doesn't require manually emitting markup. I use this because I'm rendering Razor Pages to strings and sending them out via email, which is an environment where the white-space styling won't always work.
public static IHtmlContent RenderNewlines<TModel>(this IHtmlHelper<TModel> html, string content)
{
if (string.IsNullOrEmpty(content) || html is null)
{
return null;
}
TagBuilder brTag = new TagBuilder("br");
IHtmlContent br = brTag.RenderSelfClosingTag();
HtmlContentBuilder htmlContent = new HtmlContentBuilder();
// JAS: On the off chance a browser is using LF instead of CRLF we strip out CR before splitting on LF.
string lfContent = content.Replace("\r", string.Empty, StringComparison.InvariantCulture);
string[] lines = lfContent.Split('\n', StringSplitOptions.None);
foreach(string line in lines)
{
_ = htmlContent.Append(line);
_ = htmlContent.AppendHtml(br);
}
return htmlContent;
}
In TypeScript you can do a type assertion using an interface and generics like so:
var json = Utilities.JSONLoader.loadFromFile("../docs/location_map.json");
var locations: Array<ILocationMap> = JSON.parse(json).location;
Where ILocationMap describes the shape of your data. The advantage of this method is that your JSON could contain more properties but the shape satisfies the conditions of the interface.
However, this does NOT add class instance methods.
Too late but in case someone need it:
fun setDrawableColor(drawable: Drawable, color: Int) :Drawable {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
drawable.colorFilter = BlendModeColorFilter(color, BlendMode.SRC_ATOP)
return drawable
} else {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
return drawable
}
}
If you would like to output array within string using puts
, you will get the same result as if you were using print
:
puts "#{[0, 1, nil]}":
[0, 1, nil]
But if not withing a quoted string then yes. The only difference is between new line when we use puts
.
Also see PEP 263 if you are using a non-ascii characterset
Abstract
This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.
Problem
In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape". This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals.
Proposed Solution
I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.
To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given.
To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:
# coding=<encoding name>
or (using formats recognized by popular editors)
#!/usr/bin/python # -*- coding: <encoding name> -*-
or
#!/usr/bin/python # vim: set fileencoding=<encoding name> :
...
I got the same error but from a backend job (SSIS job). Upon checking the database's Log file growth setting, the log file was limited growth of 1GB. So what happened is when the job ran and it asked SQL server to allocate more log space, but the growth limit of the log declined caused the job to failed. I modified the log growth and set it to grow by 50MB and Unlimited Growth and the error went away.
try this one out.
<label for="user">user</label>
<input type="text" name="user"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue"
value="username" maxlength="19" />
hope this helps.
You can wrote **_bold and italic_**
and re-style it to underlined text, like this:
strong>em,
em>strong,
b>i,
i>b {
font-style:normal;
font-weight:normal;
text-decoration:underline;
}
The problem is the tv.setText(text)
. The variable tv is probably null
and you call the setText
method on that null
, which you can't.
My guess that the problem is on the findViewById
method, but it's not here, so I can't tell more, without the code.
String array = array of characters ?
Or do you have a string with multiple words each of which should be an array element ?
String[] array = yourString.split(wordSeparator);
declare
c int;
begin
select count(*) into c from user_tables where table_name = upper('table_name');
if c = 1 then
execute immediate 'drop table table_name';
end if;
end;
That's for checking whether a table in the current schema exists.
For checking whether a given table already exists in a different schema, you'd have to use all_tables
instead of user_tables
and add the condition all_tables.owner = upper('schema_name')
use
keyword from Command Line Interface:PHP Namespaces don't work on the commandline unless you also include or require the php file. When the php file is sitting in the webspace where it is interpreted by the php daemon then you don't need the require line. All you need is the 'use' line.
Create a new directory /home/el/bin
Make a new file called namespace_example.php
and put this code in there:
<?php
require '/home/el/bin/mylib.php';
use foobarwhatever\dingdong\penguinclass;
$mypenguin = new penguinclass();
echo $mypenguin->msg();
?>
Make another file called mylib.php
and put this code in there:
<?php
namespace foobarwhatever\dingdong;
class penguinclass
{
public function msg() {
return "It's a beautiful day chris, come out and play! " .
"NO! *SLAM!* taka taka taka taka.";
}
}
?>
Run it from commandline like this:
el@apollo:~/bin$ php namespace_example.php
Which prints:
It's a beautiful day chris, come out and play!
NO! *SLAM!* taka taka taka taka
See notes on this in the comments here: http://php.net/manual/en/language.namespaces.importing.php
Use this:
Format(Now, "MMMM dd, yyyy")
More: Format Function
I had the issue the imports for the routing module must come after the child module, this might not be directly related to this post but it would have helped me if I read this:
https://angular.io/guide/router#module-import-order-matters
imports: [
BrowserModule,
FormsModule,
ChildModule,
AppRoutingModule
],
I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.
I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.
from PIL import Image
import os, os.path
imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append(Image.open(os.path.join(path,f)))
DDL is Data Definition Language: Just think you are defining the DB.
So we use CREATE,ALTER TRUNCATE commands.
DML is after defining we are Manipulating the data. So we use SELECT,INSERT, UPDATE, DELETE command.
Remember DDL commands are auto-committed. You don't need to use COMMIT statements.
DML (Data Manipulation Language) commands need to be commited/rolled back.
Usually I create Fowler's Range implementation for such things.
public interface IRange<T>
{
T Start { get; }
T End { get; }
bool Includes(T value);
bool Includes(IRange<T> range);
}
public class DateRange : IRange<DateTime>
{
public DateRange(DateTime start, DateTime end)
{
Start = start;
End = end;
}
public DateTime Start { get; private set; }
public DateTime End { get; private set; }
public bool Includes(DateTime value)
{
return (Start <= value) && (value <= End);
}
public bool Includes(IRange<DateTime> range)
{
return (Start <= range.Start) && (range.End <= End);
}
}
Usage is pretty simple:
DateRange range = new DateRange(startDate, endDate);
range.Includes(date)
In XML there can be only one root element - you have two - heading
and song
.
If you restructure to something like:
<?xml version="1.0" encoding="UTF-8"?>
<song>
<heading>
The Twelve Days of Christmas
</heading>
....
</song>
The error about well-formed XML on the root level should disappear (though there may be other issues).
instead of join()
, which is an old API, you can use CountDownLatch. I have modified your code as below to fulfil your requirement.
import java.util.concurrent.*;
class DoSomethingInAThread implements Runnable{
CountDownLatch latch;
public DoSomethingInAThread(CountDownLatch latch){
this.latch = latch;
}
public void run() {
try{
System.out.println("Do some thing");
latch.countDown();
}catch(Exception err){
err.printStackTrace();
}
}
}
public class CountDownLatchDemo {
public static void main(String[] args) {
try{
CountDownLatch latch = new CountDownLatch(1000);
for (int n=0; n<1000; n++) {
Thread t = new Thread(new DoSomethingInAThread(latch));
t.start();
}
latch.await();
System.out.println("In Main thread after completion of 1000 threads");
}catch(Exception err){
err.printStackTrace();
}
}
}
Explanation:
CountDownLatch
has been initialized with given count 1000 as per your requirement.
Each worker thread DoSomethingInAThread
will decrement the CountDownLatch
, which has been passed in constructor.
Main thread CountDownLatchDemo
await()
till the count has become zero. Once the count has become zero, you will get below line in output.
In Main thread after completion of 1000 threads
More info from oracle documentation page
public void await()
throws InterruptedException
Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.
Refer to related SE question for other options:
I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud
claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)
For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)
For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).
OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud
claim in ID Tokens. (openid-connect-core-1.0)
aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.
furthermore OIDC specifies the azp
claim that is used in conjunction with aud
when aud
has more than one value.
azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.
I originally found this post looking for a solution to copying stored procedures from my remote production database to my local development database. After success using the suggested approach in this thread, I realized I grew increasingly lazy (or resourceful, whichever you prefer) and wanted this to be automated. I came across this link, which proved to be very helpful (thank you vincpa), and I extended upon it, resulting in the following file (schema_backup.ps1):
$server = "servername"
$database = "databaseName"
$output_path = "D:\prod_schema_backup"
$login = "username"
$password = "password"
$schema = "dbo"
$table_path = "$output_path\table\"
$storedProcs_path = "$output_path\stp\"
$views_path = "$output_path\view\"
$udfs_path = "$output_path\udf\"
$textCatalog_path = "$output_path\fulltextcat\"
$udtts_path = "$output_path\udtt\"
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | out-null
$srvConn = new-object Microsoft.SqlServer.Management.Common.ServerConnection
$srvConn.ServerInstance = $server
$srvConn.LoginSecure = $false
$srvConn.Login = $login
$srvConn.Password = $password
$srv = New-Object Microsoft.SqlServer.Management.SMO.Server($srvConn)
$db = New-Object ("Microsoft.SqlServer.Management.SMO.Database")
$tbl = New-Object ("Microsoft.SqlServer.Management.SMO.Table")
$scripter = New-Object Microsoft.SqlServer.Management.SMO.Scripter($srvConn)
# Get the database and table objects
$db = $srv.Databases[$database]
$tbl = $db.tables | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject }
$storedProcs = $db.StoredProcedures | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject }
$views = $db.Views | Where-object { $_.schema -eq $schema }
$udfs = $db.UserDefinedFunctions | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject }
$catlog = $db.FullTextCatalogs
$udtts = $db.UserDefinedTableTypes | Where-object { $_.schema -eq $schema }
# Set scripter options to ensure only data is scripted
$scripter.Options.ScriptSchema = $true;
$scripter.Options.ScriptData = $false;
#Exclude GOs after every line
$scripter.Options.NoCommandTerminator = $false;
$scripter.Options.ToFileOnly = $true
$scripter.Options.AllowSystemObjects = $false
$scripter.Options.Permissions = $true
$scripter.Options.DriAllConstraints = $true
$scripter.Options.SchemaQualify = $true
$scripter.Options.AnsiFile = $true
$scripter.Options.SchemaQualifyForeignKeysReferences = $true
$scripter.Options.Indexes = $true
$scripter.Options.DriIndexes = $true
$scripter.Options.DriClustered = $true
$scripter.Options.DriNonClustered = $true
$scripter.Options.NonClusteredIndexes = $true
$scripter.Options.ClusteredIndexes = $true
$scripter.Options.FullTextIndexes = $true
$scripter.Options.EnforceScriptingOptions = $true
function CopyObjectsToFiles($objects, $outDir) {
#clear out before
Remove-Item $outDir* -Force -Recurse
if (-not (Test-Path $outDir)) {
[System.IO.Directory]::CreateDirectory($outDir)
}
foreach ($o in $objects) {
if ($o -ne $null) {
$schemaPrefix = ""
if ($o.Schema -ne $null -and $o.Schema -ne "") {
$schemaPrefix = $o.Schema + "."
}
#removed the next line so I can use the filename to drop the stored proc
#on the destination and recreate it
#$scripter.Options.FileName = $outDir + $schemaPrefix + $o.Name + ".sql"
$scripter.Options.FileName = $outDir + $schemaPrefix + $o.Name
Write-Host "Writing " $scripter.Options.FileName
$scripter.EnumScript($o)
}
}
}
# Output the scripts
CopyObjectsToFiles $tbl $table_path
CopyObjectsToFiles $storedProcs $storedProcs_path
CopyObjectsToFiles $views $views_path
CopyObjectsToFiles $catlog $textCatalog_path
CopyObjectsToFiles $udtts $udtts_path
CopyObjectsToFiles $udfs $udfs_path
Write-Host "Finished at" (Get-Date)
$srv.ConnectionContext.Disconnect()
I have a .bat file that calls this, and is called from Task Scheduler. After the call to the Powershell file, I have:
for /f %f in ('dir /b d:\prod_schema_backup\stp\') do sqlcmd /S localhost /d dest_db /Q "DROP PROCEDURE %f"
That line will go thru the directory and drop the procedures it is going to recreate. If this wasn't a development environment, I would not like programmatically dropping procedures this way. I then rename all the stored procedure files to have .sql:
powershell Dir d:\prod_schema_backup\stp\ | Rename-Item -NewName { $_.name + ".sql" }
And then run:
for /f %f in ('dir /b d:\prod_schema_backup\stp\') do sqlcmd /S localhost /d dest_db /E /i "%f".sql
And that iterates through all the .sql files and recreates the stored procedures. I hope that any part of this will prove to be helpful to someone.
What you have initialized is a vector of vectors, so you definitely have to include a vector to be inserted("Pushed" in the terminology of vectors) in the original vector you have named matrix in your example.
One more thing, you cannot directly insert values in the vector using the operator "cin". Use a variable which takes input and then insert the same in the vector.
Please try this out :
int num;
for(int i=0; i<RR; i++){
vector<int>inter_mat; //Intermediate matrix to help insert(push) contents of whole row at a time
for(int j=0; j<CC; j++){
cin>>num; //Extra variable in helping push our number to vector
vin.push_back(num); //Inserting numbers in a row, one by one
}
v.push_back(vin); //Inserting the whole row at once to original 2D matrix
}
You can also use the built-in forensic log feature.
It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!
The only times you should need to escape are when trying to put "
inside a string, or '
in a character:
String quotes = "He said \"Hello, World!\"";
char quote = '\'';
Update: Angular 8 finally got method to clear the Array FormArray.clear()
I manually filled NAs by exporting the CSV then editing it and reimporting, as below.
Perhaps one of you experts might explain why this procedure worked so well
(the first file had columns with data of types char
, INT
and num
(floating point numbers)), which all became char
type after STEP 1; but at the end of STEP 3 R correctly recognized the datatype of each column).
# STEP 1:
MainOptionFile <- read.csv("XLUopt_XLUstk_v3.csv",
header=T, stringsAsFactors=FALSE)
#... STEP 2:
TestFrame <- subset(MainOptionFile, str_locate(option_symbol,"120616P00034000") > 0)
write.csv(TestFrame, file = "TestFrame2.csv")
# ...
# STEP 3:
# I made various amendments to `TestFrame2.csv`, including replacing all missing data cells with appropriate numbers. I then read that amended data frame back into R as follows:
XLU_34P_16Jun12 <- read.csv("TestFrame2_v2.csv",
header=T,stringsAsFactors=FALSE)
On arrival back in R, all columns had their correct measurement levels automatically recognized by R!
I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.
You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element.
.menuItem
{
display: inline;
background-color: #000;
/* width and height should not work on inline elements */
/* if this works, your browser is doing the rendering */
/* in quirks mode which will not be compatible with */
/* other browsers - but this will not work on touch mobile devices like android */
}
.menuItem a:hover
{
background-color:#F00;
}
You have to use GetThumbnailImage
method in the Image
class:
https://msdn.microsoft.com/en-us/library/8t23aykb%28v=vs.110%29.aspx
Here's a rough example that takes an image file and makes a thumbnail image from it, then saves it back to disk.
Image image = Image.FromFile(fileName);
Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero);
thumb.Save(Path.ChangeExtension(fileName, "thumb"));
It is in the System.Drawing namespace (in System.Drawing.dll).
Behavior:
If the Image contains an embedded thumbnail image, this method retrieves the embedded thumbnail and scales it to the requested size. If the Image does not contain an embedded thumbnail image, this method creates a thumbnail image by scaling the main image.
Important: the remarks section of the Microsoft link above warns of certain potential problems:
The
GetThumbnailImage
method works well when the requested thumbnail image has a size of about 120 x 120 pixels. If you request a large thumbnail image (for example, 300 x 300) from an Image that has an embedded thumbnail, there could be a noticeable loss of quality in the thumbnail image.It might be better to scale the main image (instead of scaling the embedded thumbnail) by calling the
DrawImage
method.
NUMBER (precision, scale)
means precision
number of total digits, of which scale
digits are right of the decimal point.
NUMBER(2,2)
in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2)
to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.
we had similar header issue with Amazon (AWS) S3 presigned Post failing on some browsers.
point was to tell bucket CORS to expose header <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
more details in this answer: https://stackoverflow.com/a/37465080/473040
An answer has already been accepted, but in these situations, a more elegant solution in my opinion would be to use error handling.
try {
$user = User::where('mobile', Input::get('mobile'))->first();
} catch (ErrorException $e) {
// Do stuff here that you need to do if it doesn't exist.
return View::make('some.view')->with('msg', $e->getMessage());
}
In addition to zombat's answer if you keep forgetting stdClass
function object(){
return new stdClass();
}
Now you can do:
$str='';
$array=array();
$object=object();
If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:
Let's say you have following package structure in your python project:
in - com.my.func.DifferentFunction
python file you have some function, like:
def add(arg1, arg2):
return arg1 + arg2
def sub(arg1, arg2) :
return arg1 - arg2
def mul(arg1, arg2) :
return arg1 * arg2
And you want to call different functions from Example3.py
, then following way you can do it:
Define import statement in Example3.py
- file for import all function
from com.my.func.DifferentFunction import *
or define each function name which you want to import
from com.my.func.DifferentFunction import add, sub, mul
Then in Example3.py
you can call function for execute:
num1 = 20
num2 = 10
print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))
Output:
add : 30
sub : 10
mul : 200
In your case use data==null
(which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)
function test(data) {_x000D_
if (data != null) {_x000D_
console.log('Data: ', data);_x000D_
}_x000D_
}_x000D_
_x000D_
test(); // the data=undefined_x000D_
test(null); // the data=null_x000D_
test(undefined); // the data=undefined_x000D_
_x000D_
test(0); _x000D_
test(false); _x000D_
test('something');
_x000D_
Here you have all (src):
if
== (its negation !=)
=== (its negation !==)
this function returns the difference in years between two dates (taken as strings in ISO format, but it can easily modified to take in any format)
import time
def years(earlydateiso, laterdateiso):
"""difference in years between two dates in ISO format"""
ed = time.strptime(earlydateiso, "%Y-%m-%d")
ld = time.strptime(laterdateiso, "%Y-%m-%d")
#switch dates if needed
if ld < ed:
ld, ed = ed, ld
res = ld[0] - ed [0]
if res > 0:
if ld[1]< ed[1]:
res -= 1
elif ld[1] == ed[1]:
if ld[2]< ed[2]:
res -= 1
return res
If you already have a table pre_loaded_tbl with some data. You can use a trick to load the data into your table with following query
INSERT INTO TABLE tweet_table
SELECT "my_data" AS my_column
FROM pre_loaded_tbl
LIMIT 5;
Also please note that "my_data" is independent of any data in the pre_loaded_tbl. You can select any data and write any column name (here my_data and my_column). Hive does not require it to have same column name. However structure of select statement should be same as that of your tweet_table. You can use limit to determine how many times you can insert into the tweet_table.
However if you haven't' created any table, you will have to load the data using file copy or load data commands in above answers.
(1) Is it possible to pass a JSON object to the url like in Ex.2?
No, because http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}
is not a valid URL.
If you want to do it the RESTful way, use http://localhost:8080/api/v1/mno/objectKey/1/Saif
, and defined your method like this:
@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)
public Book getBook(@PathVariable int id, @PathVariable String name) {
// code here
}
(2) How can we pass and parse the parameters in Ex.1?
Just add two request parameters, and give the correct path.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)
public Book getBook(@RequestParam int id, @RequestParam String name) {
// code here
}
UPDATE (from comment)
What if we have a complicated parameter structure ?
"A": [ { "B": 37181, "timestamp": 1160100436, "categories": [ { "categoryID": 2653, "timestamp": 1158555774 }, { "categoryID": 4453, "timestamp": 1158555774 } ] } ]
Send that as a POST
with the JSON data in the request body, not in the URL, and specify a content type of application/json
.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")
public Book getBook(@RequestBody ObjectKey objectKey) {
// code here
}
In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.
git rebase -i origin/master
Then, your commits will appear:
pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments
Select the commit you want to reword and save.
pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments
Now, you have the opportunity to add header and body, where the first line will be the header.
Create perpetuum mobile
Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.
I was having a similar problem that I could not resolve for a long time on my new server. In addition to palacsint's answer, a good question to ask is: are you using Apache 2.4? In Apache 2.4 there is a different mechanism for setting the permissions that do not work when done using the above configuration, so I used the solution explained in this blog post.
Basically, what I needed to do was convert my config file from:
Alias /demo /usr/demo/html
<Directory "/usr/demo/html">
Options FollowSymLinks
AllowOverride None
Order allow,deny
allow from all
</Directory>
to:
Alias /demo /usr/demo/html
<Directory "/usr/demo/html">
Options FollowSymLinks
AllowOverride None
Require all granted
</Directory>
Note how the Order and allow lines have been replaced by Require all granted
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
This should handle cases of clicking on [x] or ALT+F4
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult result = MessageBox.Show("Do you really want to exit?", "Dialog Title", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
Environment.Exit(0);
}
else
{
e.Cancel = true;
}
}
else
{
e.Cancel = true;
}
}
From the manual:
-N or --LINE-NUMBERS Causes a line number to be displayed at the beginning of each line in the display.
You can also toggle line numbers without quitting less by typing -N
.
It is possible to toggle any of less's command line options in this way.
I know it's a really old question, but it's the first result on duckduckgo, so I wanted to share what I think it's a better and more modern solution.
You can use background-blend-mode
property to achieve a greyscale image:
#something {
background-color: #fff;
background-image: url("yourimage");
background-blend-mode: luminosity;
}
If you want to remove the effect, just change the blend-mode to initial
.
You may need to play a little bit with the background-color if this element is over something with a background. What I've found is that the greyscale does not depend on the actual color but on the alpha value. So, if you have a blue background on the parent, set the same background on #something
.
You can also use two images, one with color and the other without and set both as background and play with other blend modes.
https://www.w3schools.com/cssref/pr_background-blend-mode.asp
It won't work on Edge though.
EDIT: I've miss the "fade" part of the question.
If you wan't to make it fade from/to grayscale, you can use a css transition on the background color changeing it's alpha value:
#something {
background-color: rgba(255,255,255,1);
background-image: url("yourimage");
background-blend-mode: luminosity;
transition: background-color 1s ease-out;
}
#something:hover {
background-color: rgba(255,255,255,0);
}
I'm also adding a codepen example for completeness https://codepen.io/anon/pen/OBKKVZ
The typical way to achieve this is to export to CSV and then load the CSV into Excel.
You can using any MySQL command line tool to do this by including the INTO OUTFILE
clause on your SELECT
statement:
SELECT ... FROM ... WHERE ...
INTO OUTFILE 'file.csv'
FIELDS TERMINATED BY ','
See this link for detailed options.
Alternatively, you can use mysqldump to store dump into a separated value format using the --tab option, see this link.
mysqldump -u<user> -p<password> -h<host> --where=jtaskResult=2429 --tab=<file.csv> <database> TaskResult
Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv'
or INTO OUTFILE './output.csv'
, it will store the output file to the directory specified by show variables like 'datadir';
.
If you use C++11, you can use the specifier "override", and it will give you a compiler error if your aren't correctly overriding an abstract method. You probably have a method that doesn't match exactly with an abstract method in the base class, so your aren't actually overriding it.
Try this code, considers it only if you need the back button.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//YOUR CODE
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//YOUR CODE
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed();
return true;
}
I know it's a very old comment, but still:
Instead of using single bracket (dfTest['A'])
, use double brackets (dfTest[['A']])
.
i.e: min_max_scaler.fit_transform(dfTest[['A']])
.
I believe this will give the desired result.
For circle, create a div element and then enter width = 2 times of the border radius = 2 times padding. Also line-height = 0 For example, with 50px as radii of the circle, the below code works well:
width: 100px;
padding: 50px 0;
border: solid;
line-height: 0px;
border-radius: 50px;
Take a look at this WPF metro-styled window with optional glowing borders.
This is a stand-alone application using no other libraries than Microsoft.Windows.Shell (included) to create metro-styled windows with optional glowing borders.
Supports Windows all the way back to XP (.NET4).
To install or upgrade pip, download get-pip.py from the official site. Then run the following command:
sudo python get-pip.py
and it will install pip
for your python version which runs the script.
You can't do this. A File
is just an abstract way to refer to a file in the file system. It doesn't contain any of the file contents itself.
If you're trying to create an in-memory file that can be referred to using a File
object, you aren't going to be able to do that, either, as explained in this thread, this thread, and many other places..
For long time I was looking for a function able to properly decompose file path. For me this code is working perfectly for both Linux and Windows.
void decomposePath(const char *filePath, char *fileDir, char *fileName, char *fileExt)
{
#if defined _WIN32
const char *lastSeparator = strrchr(filePath, '\\');
#else
const char *lastSeparator = strrchr(filePath, '/');
#endif
const char *lastDot = strrchr(filePath, '.');
const char *endOfPath = filePath + strlen(filePath);
const char *startOfName = lastSeparator ? lastSeparator + 1 : filePath;
const char *startOfExt = lastDot > startOfName ? lastDot : endOfPath;
if(fileDir)
_snprintf(fileDir, MAX_PATH, "%.*s", startOfName - filePath, filePath);
if(fileName)
_snprintf(fileName, MAX_PATH, "%.*s", startOfExt - startOfName, startOfName);
if(fileExt)
_snprintf(fileExt, MAX_PATH, "%s", startOfExt);
}
Example results are:
[]
fileDir: ''
fileName: ''
fileExt: ''
[.htaccess]
fileDir: ''
fileName: '.htaccess'
fileExt: ''
[a.exe]
fileDir: ''
fileName: 'a'
fileExt: '.exe'
[a\b.c]
fileDir: 'a\'
fileName: 'b'
fileExt: '.c'
[git-archive]
fileDir: ''
fileName: 'git-archive'
fileExt: ''
[git-archive.exe]
fileDir: ''
fileName: 'git-archive'
fileExt: '.exe'
[D:\Git\mingw64\libexec\git-core\.htaccess]
fileDir: 'D:\Git\mingw64\libexec\git-core\'
fileName: '.htaccess'
fileExt: ''
[D:\Git\mingw64\libexec\git-core\a.exe]
fileDir: 'D:\Git\mingw64\libexec\git-core\'
fileName: 'a'
fileExt: '.exe'
[D:\Git\mingw64\libexec\git-core\git-archive.exe]
fileDir: 'D:\Git\mingw64\libexec\git-core\'
fileName: 'git-archive'
fileExt: '.exe'
[D:\Git\mingw64\libexec\git.core\git-archive.exe]
fileDir: 'D:\Git\mingw64\libexec\git.core\'
fileName: 'git-archive'
fileExt: '.exe'
[D:\Git\mingw64\libexec\git-core\git-archiveexe]
fileDir: 'D:\Git\mingw64\libexec\git-core\'
fileName: 'git-archiveexe'
fileExt: ''
[D:\Git\mingw64\libexec\git.core\git-archiveexe]
fileDir: 'D:\Git\mingw64\libexec\git.core\'
fileName: 'git-archiveexe'
fileExt: ''
I hope this helps you also :)
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
With query syntax:
var values =
from inner in outer
from value in inner
select value;
If you want to move files around and keep the csproj files up to date, the easiest way is to use a Visual Studio plugin like AnkhSVN. That will automatically commit both the move action (as an delete + add with history, because that's how Subversion works) and a change in the .csproj
You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).
Here's a function that does what you want:
import re
def is_match(regex, text):
pattern = re.compile(regex, text)
return pattern.search(text) is not None
The regular expression search method returns an object on success and None if the pattern is not found in the string. With that in mind, we return True as long as the search gives us something back.
Examples:
>>> is_match('ba[rzd]', 'foobar')
True
>>> is_match('ba[zrd]', 'foobaz')
True
>>> is_match('ba[zrd]', 'foobad')
True
>>> is_match('ba[zrd]', 'foobam')
False
Simplest way to throw an Exception in C++:
#include <iostream>
using namespace std;
void purturb(){
throw "Cannot purturb at this time.";
}
int main() {
try{
purturb();
}
catch(const char* msg){
cout << "We caught a message: " << msg << endl;
}
cout << "done";
return 0;
}
This prints:
We caught a message: Cannot purturb at this time.
done
If you catch the thrown exception, the exception is contained and the program will ontinue. If you do not catch the exception, then the program exists and prints:
This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
Simple, [yourobject class] it will return the class name of yourobject.
Edit 08/13/2018: There is now support for native array operations in Cloud Firestore. See Doug's answer below.
There is currently no way to update a single array element (or add/remove a single element) in Cloud Firestore.
This code here:
firebase.firestore()
.collection('proprietary')
.doc(docID)
.set(
{ sharedWith: [{ who: "[email protected]", when: new Date() }] },
{ merge: true }
)
This says to set the document at proprietary/docID
such that sharedWith = [{ who: "[email protected]", when: new Date() }
but to not affect any existing document properties. It's very similar to the update()
call you provided however the set()
call with create the document if it does not exist while the update()
call will fail.
So you have two options to achieve what you want.
Option 1 - Set the whole array
Call set()
with the entire contents of the array, which will require reading the current data from the DB first. If you're concerned about concurrent updates you can do all of this in a transaction.
Option 2 - Use a subcollection
You could make sharedWith
a subcollection of the main document. Then
adding a single item would look like this:
firebase.firestore()
.collection('proprietary')
.doc(docID)
.collection('sharedWith')
.add({ who: "[email protected]", when: new Date() })
Of course this comes with new limitations. You would not be able to query
documents based on who they are shared with, nor would you be able to
get the doc and all of the sharedWith
data in a single operation.
I know this is an old question, but I think found a very simple answer, in case anybody needs it.
If you put string quotes inside your string ("'hello'"), ast_literaleval() will understand it perfectly.
You can use a simple function:
def doubleStringify(a):
b = "\'" + a + "\'"
return b
Or probably more suitable for this example:
def perfectEval(anonstring):
try:
ev = ast.literal_eval(anonstring)
return ev
except ValueError:
corrected = "\'" + anonstring + "\'"
ev = ast.literal_eval(corrected)
return ev
You should put android:inputType="textCapCharacters"
with Edittext in xml file.
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
I'm answering this question from the larger question:
When I add $locationProvider.html5Mode(true), my site will not allow pasting of urls. How do I configure my server to work when html5Mode is true?
When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some examples:
For Express Rewrites with AngularJS, you can solve this with the following updates:
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});
and
<!-- FOR ANGULAR ROUTING -->
<base href="/">
and
app.use('/',express.static(__dirname + '/public'));
How to kill a windows service using PID -
netstat -ano
taskkill /f /pid 5760
Thanks
As I found this question is old and have many answers but I have an answer which is simple and working great..
#define EPSILON 0.0000001 // least minimum value for comparison
double SquareRoot(double _val) {
double low = 0;
double high = _val;
double mid = 0;
while (high - low > EPSILON) {
mid = low + (high - low) / 2; // finding mid value
if (mid*mid > _val) {
high = mid;
} else {
low = mid;
}
}
return mid;
}
I hope it will be helpful for future users.
Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.
The following is from the Secure Coding Guidelines 2.0.
Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).
Quoting an article at programming.guide:
this
has two uses in a Java program.
The syntax in this case usually looks something like
this.someVariable = someVariable;
This type of use is described here: The 'this' reference (with examples)
The syntax in this case typically looks something like
MyClass() {
this(DEFAULT_VALUE); // delegate to other constructor
}
MyClass(int value) {
// ...
}
This type of use is described here: this(…) constructor call (with examples)
1 - remove the margin from your BODY CSS.
2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>
3 - Define the CSS for the wrapper:
This will hold everything together, centered on the page.
#wrapper {
margin-left:auto;
margin-right:auto;
width:960px;
}
The reason this is failing is because (Python 3) input
returns a string. To convert it to an integer, use int(some_string)
.
You do not typically keep track of indices manually in Python. A better way to implement such a function would be
def cat_n_times(s, n):
for i in range(n):
print(s)
text = input("What would you like the computer to repeat back to you: ")
num = int(input("How many times: ")) # Convert to an int immediately.
cat_n_times(text, num)
I changed your API above a bit. It seems to me that n
should be the number of times and s
should be the string.
From https://www.w3schools.com/css/css_boxmodel.asp
Explanation of the different parts:
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
Live example (play around by changing the values): https://www.w3schools.com/css/tryit.asp?filename=trycss_boxmodel
Two options:
char c1 = '\u0001';
char c1 = (char) 1;
Unfortunately, there is none. You can use the System.Collections.Generic.KeyValuePair<K, V>
in many situations.
Alternatively, you can use anonymous types to handle tuples, at least locally:
var x = new { First = "x", Second = 42 };
The last alternative is to create an own class.
size param increases the hits displayed from from the default(10) to 500.
http://localhost:9200/[indexName]/_search?pretty=true&size=500&q=*:*
Change the from step by step to get all the data.
http://localhost:9200/[indexName]/_search?size=500&from=0
In the first place, you should note that PDF and HTML and different formats that hardly have anything in common. If TCPDF allows you to provide input data using HTML and CSS it's because it implements a simple parser for these two languages and tries to figure out how to translate that into PDF. So it's logical that TCPDF only supports a little subset of the HTML and CSS specification and, even in supported stuff, it's probably not as perfect as in first class web browsers.
Said that, the question is: what's supported and what's not? The documentation basically skips the issue and let's you enjoy the trial and error method.
Having a look at the source code, we can see there's a protected method called TCPDF::getHtmlDomArray()
that, among other things, parses CSS declarations. I can see stuff like font-family
, list-style-type
or text-indent
but there's no margin
or padding
as far as I can see and, definitively, there's no float
at all.
To sum up: with TCPDF, you can use CSS for some basic formatting. If you need to convert from HTML to PDF, it's the wrong tool. (If that's the case, may I suggest wkhtmltopdf?)
You convert type np.dot(X, T)
to float32 like this:
z=np.array(np.dot(X, T),dtype=np.float32)
def sigmoid(X, T):
return (1.0 / (1.0 + np.exp(-z)))
Hopefully it will finally work!
You might need to set permissions at the database level that allows your schema owner to restore the dump.
Copy the directory named npm
from your installed node path (In my case the npm directory was available in C:\Program Files\nodejs\node_modules
).
Navigate to C:\Users\%USERNAME%\AppData\Roaming\npm\node_modules
and paste the copied npm
directory there.
This method worked for me when I had the same error. . .
Although its a long time but this relatively small piece of code seems easy to read and get:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int index;
string cellContent;
foreach (TableCell tc in ((GridView)sender).HeaderRow.Cells)
{
if( tc.Text.Equals("yourColumnName") )
{
index = ((GridView)sender).HeaderRow.Cells.GetCellIndex(tc);
cellContent = ((GridView)sender).SelectedRow.Cells[index].Text;
break;
}
}
}
In Project Structure in Project SDK: modify SDK to 11 or higher and in Project language level: modify to 11 - Local variable syntax for lambda parameters
The corners are actually in .modal-content
So you may try this:
.modal-content {
background-color: #0480be;
}
.modal-body {
background-color: #fff;
}
If you change the color of the header or footer, the rounded corners will be drawn over.
In recent browsers you can use:
Object.keys(obj.Data).length
See MDN
For older browsers, use the for-in
loop in Michael Geary's answer.
*nix provides a nice little command which makes our lives a lot easier.
GET:
with JSON:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource
with XML:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource
POST:
For posting data:
curl --data "param1=value1¶m2=value2" http://hostname/resource
For file upload:
curl --form "[email protected]" http://hostname/resource
RESTful HTTP Post:
curl -X POST -d @filename http://hostname/resource
For logging into a site (auth):
curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/
Pretty-printing the curl results:
For JSON:
If you use npm
and nodejs
, you can install json
package by running this command:
npm install -g json
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json
If you use pip
and python
, you can install pjson
package by running this command:
pip install pjson
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson
If you use Python 2.6+, json tool is bundled within.
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool
If you use gem
and ruby
, you can install colorful_json
package by running this command:
gem install colorful_json
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson
If you use apt-get
(aptitude package manager of your Linux distro), you can install yajl-tools
package by running this command:
sudo apt-get install yajl-tools
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json_reformat
For XML:
If you use *nix with Debian/Gnome envrionment, install libxml2-utils
:
sudo apt-get install libxml2-utils
Usage:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -
or install tidy
:
sudo apt-get install tidy
Usage:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -
Saving the curl response to a file
curl http://hostname/resource >> /path/to/your/file
or
curl http://hostname/resource -o /path/to/your/file
For detailed description of the curl command, hit:
man curl
For details about options/switches of the curl command, hit:
curl -h
var arr = [1, 2, 3];
arr.slice(-1).pop(); // return 3 and arr = [1, 2, 3]
This will return undefined if the array is empty and this will not change the value of the array.
As I understand it, this is the default way of using the web driver.
in textView
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:onClick="onClick"
android:clickable="true"
You must also implement View.OnClickListener and in On Click method can use intent
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://youraddress.com"));
startActivity(intent);
I tested this solution works fine.
The below code is to add 4 hours to date(example today's date)
var today = new Date();
today.setHours(today.getHours() + 4);
It will not cause error if you try to add 4 to 23 (see the docs):
If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly
Karan Bhandari's answer is good, but the AccountController added in a project is very likely a Mvc.Controller
. To convert his answer for use in an ApiController change HttpContext.Current.GetOwinContext()
to Request.GetOwinContext()
and make sure you have added the following 2 using
statements:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
Here's a Swift version of Paul Lynch's answer
func imageWithImage(image:UIImage, scaledToSize newSize:CGSize) -> UIImage{
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
And as an extension:
public extension UIImage {
func copy(newSize: CGSize, retina: Bool = true) -> UIImage? {
// In next line, pass 0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(
/* size: */ newSize,
/* opaque: */ false,
/* scale: */ retina ? 0 : 1
)
defer { UIGraphicsEndImageContext() }
self.draw(in: CGRect(origin: .zero, size: newSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
better code that doesn't involve ping:
SET COUNTER=0
:loop
SET /a COUNTER=%COUNTER%+1
XCOPY "Server\*" "c:\minecraft\backups\server_backup_%COUNTER%" /i /s
timeout /t 600 /nobreak >nul
goto loop
600 seconds is 10 minutes, however you can set it whatever time you'd like
To decode json, you have to pass the json string. Currently you're trying to pass an object:
>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>
You can fetch the data with response.read()
.
Regarding int main():
According to the Standard, argv
points to a NULL-terminated array (of pointers to null-terminated strings). (5.1.2.2.1:1).
That is, argv = (char **){ argv[0], ..., argv[argc - 1], 0 };
.
Hence, size calculation is performed by a function which is a trivial modification of strlen()
.
argc
is only there to make argv
length calculation O(1).
The count-until-NULL method will NOT work for generic array input. You will need to manually specify size as a second argument.