[Array] $servers = "Server1","server2";
$service='YOUR SERVICE'
foreach($server in $servers)
{
$srvc = Get-WmiObject -query "SELECT * FROM win32_service WHERE name LIKE '$service' " -computername $server ;
$res=Write-Output $srvc | Format-Table -AutoSize $server, $fmtMode, $fmtState, $fmtStatus ;
$srvc.startservice()
$res
}
You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True
and create and run migration.
hash_items = {:item => 1}
puts hash_items
#hash_items will give you {:item => 1}
hash_items.merge!({:item => 2})
puts hash_items
#hash_items will give you {:item => 1, :item => 2}
hash_items.merge({:item => 2})
puts hash_items
#hash_items will give you {:item => 1, :item => 2}, but the original variable will be the same old one.
if you are findind keyboard shortcuts for Fix doc comment like this:
/**
* ...
*/
you can do it by useing Live Template(setting - editor - Live Templates - add)
/**
* $comment$
*/
Build Variants
pane, typically found along the lower left side of the window:debug
to release
shift+f10
run!!then, Android Studio will execute assembleRelease
task and install xx-release.apk to your device.
I fixed this with below steps:
Here's an example that makes sure that the body has minimum height of the device screen height and also hides the scroll bar. It uses DOMSubtreeModified event, but makes the check only every 400ms, to avoid performance loss.
var page_size_check = null, q_body;
(q_body = $('#body')).bind('DOMSubtreeModified', function() {
if (page_size_check === null) {
return;
}
page_size_check = setTimeout(function() {
q_body.css('height', '');
if (q_body.height() < window.innerHeight) {
q_body.css('height', window.innerHeight + 'px');
}
if (!(window.pageYOffset > 1)) {
window.scrollTo(0, 1);
}
page_size_check = null;
}, 400);
});
Tested on Android and iPhone.
just add on table
style="overflow-x:auto;"
<table border=1 id="qandatbl" align="center" style="overflow-x:auto;">_x000D_
<tr>_x000D_
<th class="col1">Question No</th>_x000D_
<th class="col2">Option Type</th>_x000D_
<th class="col1">Duration</th>_x000D_
</tr>_x000D_
_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class='qid'></td>_x000D_
<td class="options"></td>_x000D_
<td class="duration"></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
style="overflow-x:auto;"`
If the resource is showing and is a view, you can also capture it. Like a screenshot:
View rootView = ((View) findViewById(R.id.yourView)).getRootView();
rootView.setDrawingCacheEnabled(true);
rootView.layout(0, 0, rootView.getWidth(), rootView.getHeight());
rootView.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
This actually grabs the whole layout but you can alter as you wish.
Something like this should do the trick
function array_max_key($array) {
$max_key = -1;
$max_val = -1;
foreach ($array as $key => $value) {
if ($value > $max_val) {
$max_key = $key;
$max_val = $value;
}
}
return $max_key;
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xyz.name"
minSdkVersion 14
targetSdkVersion 27
versionCode 7
versionName "1.6"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.volley:volley:1.0.0'
implementation 'com.wang.avi:library:2.1.3'
implementation 'com.android.support:design:27.1.0'
implementation 'com.android.support:support-v4:27.1.0'
implementation 'de.hdodenhof:circleimageview:2.1.0'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.theartofdev.edmodo:android-image-cropper:2.6.0'
implementation 'com.loopj.android:android-async-http:1.4.9'
implementation 'com.google.firebase:firebase-messaging:11.8.0'
implementation 'com.felipecsl.asymmetricgridview:library:2.0.1'
implementation 'com.android.support:recyclerview-v7:27.1.0'
implementation 'com.github.darsh2:MultipleImageSelect:3474549'
implementation 'it.sephiroth.android.library.horizontallistview:hlistview:1.2.2'
implementation 'com.android.support:multidex:1.0.1'
}
apply plugin: 'com.google.gms.google-services'
Note: update your all support library to 27.1.0 like above and remove duplicates
The best way to do this is by running the command:
git diff --name-only --cached
When you check the manual you will likely find the following:
--name-only
Show only names of changed files.
And on the example part of the manual:
git diff --cached
Changes between the index and your current HEAD.
Combined together you get the changes between the index and your current HEAD
and Show only names of changed files.
Update: --staged
is also available as an alias for --cached
above in more recent git versions.
In the absence of the ability to do zone transfers, I wrote this small bash script, dg
:
#!/bin/bash
COMMON_SUBDOMAINS=(www mail smtp pop imap blog en ftp ssh login)
if [[ "$2" == "x" ]]; then
dig +nocmd "$1" +noall +answer "${3:-any}"
wild_ips="$(dig +short "*.$1" "${3:-any}" | tr '\n' '|')"
wild_ips="${wild_ips%|}"
for sub in "${COMMON_SUBDOMAINS[@]}"; do
dig +nocmd "$sub.$1" +noall +answer "${3:-any}"
done | grep -vE "${wild_ips}"
dig +nocmd "*.$1" +noall +answer "${3:-any}"
else
dig +nocmd "$1" +noall +answer "${2:-any}"
fi
Now I use dg example.com
to get a nice, clean list of DNS records, or dg example.com x
to include a bunch of other popular subdomains.
grep -vE "${wild_ips}"
filters out records that could be the result of a wildcard DNS entry such as * 10800 IN A 1.38.216.82
. Otherwise, a wildcard entry would make it appear as if there were records for each $COMMON_SUBDOMAN
.
Note: This relies on ANY
queries, which are blocked by some DNS providers such as CloudFlare.
If it's a new implementation, you can try rewriting the logic as if-else_if-else statements.
while(keep_going) {
if(keep_going && condition_one_holds) {
// Code
}
if(keep_going && condition_two_holds) {
// Code
}
if(keep_going && condition_three_holds) {
// Code
}
if(keep_going && something_goes_really_bad) {
keep_going=false;
}
if(keep_going && condition_four_holds) {
// Code
}
if(keep_going && condition_five_holds) {
// Code
}
}
Otherwise you can try setting a flag when that special condition has occured and check for that flag in each of your loop-conditions.
something_bad_has_happened = false;
while(something is true && !something_bad_has_happened){
// Code, things happen
while(something else && !something_bad_has_happened){
// Lots of code, things happens
if(something happened){
-> Then control should be returned ->
something_bad_has_happened=true;
continue;
}
}
if(something_bad_has_happened) { // The things below will not be executed
continue;
}
// Other things may happen here as well, but they will not be executed
// once control is returned from the inner cycle.
}
HERE! So, while a simple break will not work, it can be made to work using continue
.
If you are simply porting the logic from one programming language to Java and just want to get the thing working you can try using labels.
If you install the composer as global on Ubuntu, you just need to find the composer location.
Use command
type composer
or
where composer
For Mac users, use command:
which composer
and then just remove the folder using rm
command.
function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){_x000D_
var numbers = string.toString().match(/\d+/g).join([]);_x000D_
numbers = numbers.padStart(decimals+1, "0");_x000D_
var splitNumbers = numbers.split("").reverse();_x000D_
var mask = '';_x000D_
splitNumbers.forEach(function(d,i){_x000D_
if (i == decimals) { mask = decimal + mask; }_x000D_
if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }_x000D_
mask = d + mask;_x000D_
});_x000D_
return pre + mask + pos;_x000D_
}_x000D_
var element = document.getElementById("format");_x000D_
var money= number_format("10987654321",2,',','.');_x000D_
element.innerHTML = money;
_x000D_
#format{_x000D_
display:inline-block;_x000D_
padding:10px;_x000D_
border:1px solid #ddd;_x000D_
background:#f5f5f5;_x000D_
}
_x000D_
<div id='format'>Test 123456789</div>
_x000D_
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
I present to you my ConcatenateRange VBA function (thanks Jean for the naming advice!) . It will take a range of cells (any dimension, any direction, etc.) and merge them together into a single string. As an optional third parameter, you can add a seperator (like a space, or commas sererated).
In this case, you'd write this to use it:
=ConcatenateRange(A1:A4)
Function ConcatenateRange(ByVal cell_range As range, _
Optional ByVal separator As String) As String
Dim newString As String
Dim cell As Variant
For Each cell in cell_range
If Len(cell) <> 0 Then
newString = newString & (separator & cell)
End if
Next
If Len(newString) <> 0 Then
newString = Right$(newString, (Len(newString) - Len(separator)))
End If
ConcatenateRange = newString
End Function
I just wrote this CSS and to know more, please go through: This article with vertical align anything with just 3 lines of CSS.
.element {
position: relative;
top: 50%;
transform: perspective(1px) translateY(-50%);
}
Can be done using the id of the element
example
<label><input type="radio" name="travel_mode" value="Flight" id="Flight"> Flight </label>
<label><input type="radio" name="travel_mode" value="Train" id="Train"> Train </label>
<label><input type="radio" name="travel_mode" value="Bus" id="Bus"> Bus </label>
<label><input type="radio" name="travel_mode" value="Road" id="Road"> Other </label>
js:
$('#' + selected).prop('checked',true);
Here are five ways to break out of nested loops in JavaScript:
1) Set parent(s) loop to the end
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
i = 5;
break;
}
}
}
2) Use label
exit_loops:
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
break exit_loops;
}
}
3) Use variable
var exit_loops = false;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
exit_loops = true;
break;
}
}
if (exit_loops)
break;
}
4) Use self executing function
(function()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
})();
5) Use regular function
function nested_loops()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
}
nested_loops();
just a note: CPLUS_INCLUDE_PATH
and C_INCLUDE_PATH
are not the equivalent of LD_LIBRARY_PATH
.
LD_LIBRARY_PATH
serves the ld
(the dynamic linker at runtime) whereas the equivalent of the former two that serves your C/C++ compiler with the location of libraries is LIBRARY_PATH
.
Add position: relative
to .outside
. (https://developer.mozilla.org/en-US/docs/CSS/position)
Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.
The "initial container" would be <body>
, but adding the above makes .outside
positioned.
From the asar documentation
(the use of npx
here is to avoid to install the asar
tool globally with npm install -g asar
)
npx asar extract app.asar destfolder
npx asar extract-file app.asar main.js
Developer Tools > Elements > Computed > Rendered Fonts
The picture you attached to your question shows the Style
tab. If you change to the next tab, Computed
, you can check the Rendered Fonts, that shows the actual font-family rendered.
A file descriptor is an opaque handle that is used in the interface between user and kernel space to identify file/socket resources. Therefore, when you use open()
or socket()
(system calls to interface to the kernel), you are given a file descriptor, which is an integer (it is actually an index into the processes u structure - but that is not important). Therefore, if you want to interface directly with the kernel, using system calls to read()
, write()
, close()
etc. the handle you use is a file descriptor.
There is a layer of abstraction overlaid on the system calls, which is the stdio
interface. This provides more functionality/features than the basic system calls do. For this interface, the opaque handle you get is a FILE*
, which is returned by the fopen()
call. There are many many functions that use the stdio
interface fprintf()
, fscanf()
, fclose()
, which are there to make your life easier. In C, stdin
, stdout
, and stderr
are FILE*
, which in UNIX respectively map to file descriptors 0
, 1
and 2
.
Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests
response header, indicating that the browser supports it (and in fact prefers it).
It took me 30mins of Googling, but I finally found it buried in the W3 spec.
The confusion comes because the header in the spec was HTTPS: 1
, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:
"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842
Their fix was to rename it to Upgrade-Insecure-Requests: 1
, and the spec has since been updated to match.
Anyway, here is the explanation from the W3 spec (as it appeared at the time)...
The
HTTPS
HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide....
When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.
When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a
Strict-Transport-Security
header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].
I had
numpy.array(n * [value])
in mind, but apparently that is slower than all other suggestions for large enough n
.
Here is full comparison with perfplot (a pet project of mine).
The two empty
alternatives are still the fastest (with NumPy 1.12.1). full
catches up for large arrays.
Code to generate the plot:
import numpy as np
import perfplot
def empty_fill(n):
a = np.empty(n)
a.fill(3.14)
return a
def empty_colon(n):
a = np.empty(n)
a[:] = 3.14
return a
def ones_times(n):
return 3.14 * np.ones(n)
def repeat(n):
return np.repeat(3.14, (n))
def tile(n):
return np.repeat(3.14, [n])
def full(n):
return np.full((n), 3.14)
def list_to_array(n):
return np.array(n * [3.14])
perfplot.show(
setup=lambda n: n,
kernels=[empty_fill, empty_colon, ones_times, repeat, tile, full, list_to_array],
n_range=[2 ** k for k in range(27)],
xlabel="len(a)",
logx=True,
logy=True,
)
I think the previous answers missed the most important (non-trivial) aspect of the OP's question, i.e., how to perform the search/replace in a "time saving" manner, meaning once, not three times, and "maintain case" originally present.
On the pane, check "[X] Preserve Case" before clicking the Replace All button
This performs a case-aware "smart" replacement in one pass:
apple -> orange
Apple -> Orange
APPLE -> ORANGE
Also, for peace of mind, don't forget to check the code into the VCS before performing sweeping project-wide replacements.
That's an individual question that could depend on how you're working. Some people like to put the variable type at the begining of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").
I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".
In short: english, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.
Sometimes you want to delete a file whatever the case(whatever the exception occurs ,please do delete the file). For such situations.
public static void DeleteFile(string path)
{
if (!File.Exists(path))
{
return;
}
bool isDeleted = false;
while (!isDeleted)
{
try
{
File.Delete(path);
isDeleted = true;
}
catch (Exception e)
{
}
Thread.Sleep(50);
}
}
Note:An exception is not thrown if the specified file does not exist.
You should be able to do something along the lines of the following
UPDATE s
SET
OrgAddress1 = bd.OrgAddress1,
OrgAddress2 = bd.OrgAddress2,
...
DestZip = bd.DestZip
FROM
Shipment s, ProfilerTest.dbo.BookingDetails bd
WHERE
bd.MyID = @MyId AND s.MyID2 = @MyID2
FROM statement can be made more optimial (using more specific joins), but the above should do the trick. Also, a nice side benefit to writing it this way, to see a preview of the UPDATE change UPDATE s SET
to read SELECT
! You will then see that data as it would appear if the update had taken place.
If you already have a list and want to add values from a delimited string, you can use AddRange
or InsertRange
. For example:
existingList.AddRange(names.Split(','));
brew install mysql-connector-c
CFLAGS =-I/usr/local/Cellar/mysql-connector-c/6.1.11/include pip install MySQL-python
brew unlink mysql-connector-c
require(caTools)
set.seed(101) #This is used to create same samples everytime
split1=sample.split(data$anycol,SplitRatio=2/3)
train=subset(data,split1==TRUE)
test=subset(data,split1==FALSE)
The sample.split()
function will add one extra column 'split1' to dataframe and 2/3 of the rows will have this value as TRUE and others as FALSE.Now the rows where split1 is TRUE will be copied into train and other rows will be copied to test dataframe.
You can set your cookie value containing expiry and get your expiry from cookie value.
// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);
// get
if (isset($_COOKIE["mycookie"])) {
list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}
// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee
The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.
EDIT: Is it really that confusing?
'This, is a random string'
Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.
You cant simply (directly) convert the datareader to list.
You have to loop through all the elements in datareader and insert into list
below the sample code
using (drOutput)
{
System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();
int customerId = drOutput.GetOrdinal("customerId ");
int CustomerName = drOutput.GetOrdinal("CustomerName ");
while (drOutput.Read())
{
CustomerEntity obj=new CustomerEntity ();
obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
arrObjects .Add(obj);
}
}
Use the following command outside the WEB-INF folder. This should create your war file and is the quickest method I know.
(You will need JDK 1.7+ installed and environment variables that point to the bin directory of your JDK.)
jar -cvf projectname.war *
No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:
const requestUrl = url.parse(url.format({
protocol: 'https',
hostname: 'yoursite.com',
pathname: '/the/path',
query: {
key: value
}
}));
Then make the request with the formatted url. requestUrl.path
will include the query parameters.
const req = https.get({
hostname: requestUrl.hostname,
path: requestUrl.path,
}, (res) => {
// ...
})
Old way of saving files might not work with new versions of android, starting with android10.
fun saveMediaToStorage(bitmap: Bitmap) {
//Generating a dummy file name
val filename = "${System.currentTimeMillis()}.jpg"
//Output stream
var fos: OutputStream? = null
//For devices running android >= Q
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//getting the contentResolver
context?.contentResolver?.also { resolver ->
//Content resolver will process the contentvalues
val contentValues = ContentValues().apply {
//putting file information in content values
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
}
//Inserting the contentValues to contentResolver and getting the Uri
val imageUri: Uri? =
resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
//Opening an outputstream with the Uri that we got
fos = imageUri?.let { resolver.openOutputStream(it) }
}
} else {
//These for devices running on android < Q
//So I don't think an explanation is needed here
val imagesDir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val image = File(imagesDir, filename)
fos = FileOutputStream(image)
}
fos?.use {
//Finally writing the bitmap to the output stream that we opened
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
context?.toast("Saved to Photos")
}
}
Reference- https://www.simplifiedcoding.net/android-save-bitmap-to-gallery/
When you print a string in console(Eclipse),\n,\r and \r\n have the same effect,all of them will give you a new line;but \n\r(also \n\n,\r\r) will give you two new lines;when you write a string to a file,only \r\n can give you a new line.
You don't need regex for this.
Add apache commons lang to your project (http://commons.apache.org/proper/commons-lang/), then use:
String dataYouWant = StringUtils.substringBetween(mydata, "'");
Here is a function that will do that.
CREATE FUNCTION count_str(haystack TEXT, needle VARCHAR(32))
RETURNS INTEGER DETERMINISTIC
BEGIN
RETURN ROUND((CHAR_LENGTH(haystack) - CHAR_LENGTH(REPLACE(haystack, needle, ""))) / CHAR_LENGTH(needle));
END;
Sometimes you can refactor your @Component
to use constructor or setter based injection to setup your testcase (you can and still rely on @Autowired
). Now, you can create your test entirely without a mocking framework by implementing test stubs instead (e.g. Martin Fowler's MailServiceStub):
@Component
public class MyLauncher {
private MyService myService;
@Autowired
MyLauncher(MyService myService) {
this.myService = myService;
}
// other methods
}
public class MyServiceStub implements MyService {
// ...
}
public class MyLauncherTest
private MyLauncher myLauncher;
private MyServiceStub myServiceStub;
@Before
public void setUp() {
myServiceStub = new MyServiceStub();
myLauncher = new MyLauncher(myServiceStub);
}
@Test
public void someTest() {
}
}
This technique especially useful if the test and the class under test is located in the same package because then you can use the default, package-private access modifier to prevent other classes from accessing it. Note that you can still have your production code in src/main/java
but your tests in src/main/test
directories.
If you like Mockito then you will appreciate the MockitoJUnitRunner. It allows you to do "magic" things like @Manuel showed you:
@RunWith(MockitoJUnitRunner.class)
public class MyLauncherTest
@InjectMocks
private MyLauncher myLauncher; // no need to call the constructor
@Mock
private MyService myService;
@Test
public void someTest() {
}
}
Alternatively, you can use the default JUnit runner and call the MockitoAnnotations.initMocks() in a setUp()
method to let Mockito initialize the annotated values. You can find more information in the javadoc of @InjectMocks and in a blog post that I have written.
Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Bable.
install
npm install --save asyncawait
helloz.js
var async = require('asyncawait/async');
var await = require('asyncawait/await');
(async (function testingAsyncAwait() {
await (console.log("Print me!"));
}))();
You can try following code:
foreach ($arry as $key => $value)
{
echo $key;
foreach ($value as $val)
{
echo $val;
}
}
For just a boolean match result or for a count of occurrences, you could use:
use 5.014; use strict; use warnings;
my @foo=('hello', 'world', 'foo', 'bar', 'hello world', 'HeLlo');
my $patterns=join(',',@foo);
for my $str (qw(quux world hello hEllO)) {
my $count=map {m/^$str$/i} @foo;
if ($count) {
print "I found '$str' $count time(s) in '$patterns'\n";
} else {
print "I could not find '$str' in the pattern list\n"
};
}
Output:
I could not find 'quux' in the pattern list
I found 'world' 1 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hello' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hEllO' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
Does not require to use a module.
Of course it's less "expandable" and versatile as some code above.
I use this for interactive user answers to match against a predefined set of case unsensitive answers.
I think you have downloaded the .NET Reflector & this FileGenerator plugin http://filegenreflector.codeplex.com/ , If you do,
Open up the Reflector.exe,
Go to View and click Add-Ins,
In the Add-Ins window click Add...,
Then find the dll you have downloaded
FileGenerator.dll (witch came wth the FileGenerator plugin),
Then close the Add-Ins window.
Go to File and click Open and choose the dll that you want to decompile,
After you have opend it, it will appear in the tree view,
Go to Tools and click Generate Files(Crtl+Shift+G),
select the output directory and select appropriate settings as your wish, Click generate files.
OR
subscribe to route parameter changes
// parent param listener ie: "/:id"
this.route.params.subscribe(params => {
// do something on parent param change
let parent_id = params['id']; // set slug
});
// child param listener ie: "/:id/:id"
this.route.firstChild.params.subscribe(params => {
// do something on child param change
let child_id = params['id'];
});
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
A dynamic_cast
performs a type checking using RTTI. If it fails it'll throw you an exception (if you gave it a reference) or NULL if you gave it a pointer.
You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:
Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If
This can be done as follows :
select CONVERT(VARCHAR(10), GETDATE(), 103) + ' ' + convert(VARCHAR(8), GETDATE(), 14)
Hope it helps
You can do same thing using single query
SELECT sum(if(DATE(dDate)=DATE(CURRENT_TIMESTAMP),earning,null)) astodays,
sum(if(YEARWEEK(dDate)=YEARWEEK(CURRENT_DATE),earning,null)) as weeks,
IF((MONTH(dDate) = MONTH(CURRENT_TIMESTAMP()) AND YEAR(dDate) = YEAR(CURRENT_TIMESTAMP())),sum(earning),0) AS months,
IF(YEAR(dDate) = YEAR(CURRENT_TIMESTAMP()),sum(earning),0) AS years,
sum(fAdminFinalEarning) as total_earning FROM `earning`
Hope this works.
Problem is your Xcode version is not set on Command Line Tools, to solve this problem open Xcode>Menu>preferences> location> here for Command Line tools select your Xcode version, that's it.
I saw this method on youtube hence posting here.
given infix expression : (a–b)/c*(d + e – f / g)
reverse it :
)g/f-e+d(*c/)b-a(
read characters from left to right.
maintain one stack for operators
1. if character is operand add operand to the output
2. else if character is operator or )
2.1 while operator on top of the stack has lower or **equal** precedence than this character pop
2.2 add the popped character to the output.
push the character on stack
3. else if character is parenthesis (
3.1 [ same as 2 till you encounter ) . pop ) as well
4. // no element left to read
4.1 pop operators from stack till it is not empty
4.2 add them to the output.
reverse the output and print.
credits : youtube
I continued to have this problem in ie7 when the browser was at certain widths. Turns out older browsers round the pixel value up if the percentage result isn't a whole number. To solve this you can try setting
overflow: hidden;
on the last element (or all of them).
You could write something like that :
public static bool HasMethod(this object objectToCheck, string methodName)
{
var type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
Edit : you can even do an extension method and use it like this
myObject.HasMethod("SomeMethod");
In an .htaccess
file you need to use
Deny from all
Put this in site/includes/.htaccess
to make it specific to the includes
directory
If you just wish to disallow a listing of directory files you can use
Options -Indexes
Xcode 9 • Swift 4 (also works Swift 3.x)
extension Formatter {
// create static date formatters for your date representations
static let preciseLocalTime: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "HH:mm:ss.SSS"
return formatter
}()
static let preciseGMTTime: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "HH:mm:ss.SSS"
return formatter
}()
}
extension Date {
// you can create a read-only computed property to return just the nanoseconds from your date time
var nanosecond: Int { return Calendar.current.component(.nanosecond, from: self) }
// the same for your local time
var preciseLocalTime: String {
return Formatter.preciseLocalTime.string(for: self) ?? ""
}
// or GMT time
var preciseGMTTime: String {
return Formatter.preciseGMTTime.string(for: self) ?? ""
}
}
Playground testing
Date().preciseLocalTime // "09:13:17.385" GMT-3
Date().preciseGMTTime // "12:13:17.386" GMT
Date().nanosecond // 386268973
This might help you also formatting your dates:
yourToolTip = new ToolTip();
//The below are optional, of course,
yourToolTip.ToolTipIcon = ToolTipIcon.Info;
yourToolTip.IsBalloon = true;
yourToolTip.ShowAlways = true;
yourToolTip.SetToolTip(lblYourLabel,"Oooh, you put your mouse over me.");
I just created an ArrayHelper class that would make this very easy for numeric indexes.
class ArrayHelper
{
/*
Inserts a value at the given position or throws an exception if
the position is out of range.
This function will push the current values up in index. ex. if
you insert at index 1 then the previous value at index 1 will
be pushed to index 2 and so on.
$pos: The position where the inserted value should be placed.
Starts at 0.
*/
public static function insertValueAtPos(array &$array, $pos, $value) {
$maxIndex = count($array)-1;
if ($pos === 0) {
array_unshift($array, $value);
} elseif (($pos > 0) && ($pos <= $maxIndex)) {
$firstHalf = array_slice($array, 0, $pos);
$secondHalf = array_slice($array, $pos);
$array = array_merge($firstHalf, array($value), $secondHalf);
} else {
throw new IndexOutOfBoundsException();
}
}
}
Example:
$array = array('a', 'b', 'c', 'd', 'e');
$insertValue = 'insert';
\ArrayHelper::insertValueAtPos($array, 3, $insertValue);
Beginning $array:
Array (
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
Result:
Array (
[0] => a
[1] => b
[2] => c
[3] => insert
[4] => d
[5] => e
)
Check out the DirectoryIterator class.
From one of the comments on that page:
// output all files and directories except for '.' and '..'
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
The recursive version is RecursiveDirectoryIterator.
Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.
This article explains Source Maps using a practical approach.
I had the same problem and I fixed it with:
<div id="container" style="width: 100%; height: 100%; position:absolute"></div>
The chart fits perfect to the browser even if I resize it. You can change the percentage according to your needs.
Check out ZBar reads QR Code and ECN/ISBN codes and is available as under the LGPL v2 license.
echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -- -f [email protected] -F "Elvis Presley"
or
echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -aFrom:"Elvis Presley<[email protected]>"
In .Net 5.x, update your ConfigureServices method in startup.cs with the below code
public void ConfigureServices(IServiceCollection services)
{
----------------
----------------
services.AddMvc().AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
});
------------------
}
By default, serialization (System.Text.Json.Serialization) does not support objects with cycles and does not preserve duplicate references. Use Preserve to enable unique object reference preservation on serialization and metadata consumption to read preserved references on deserialization. MSDN Link
From API 19 onwards you can make use of the Telephony Class for that; Since hardcored values won't retrieve messages in every devices because the content provider Uri changes from devices and manufacturers.
public void getAllSms(Context context) {
ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(Telephony.Sms.CONTENT_URI, null, null, null, null);
int totalSMS = 0;
if (c != null) {
totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int j = 0; j < totalSMS; j++) {
String smsDate = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.DATE));
String number = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.ADDRESS));
String body = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.BODY));
Date dateFormat= new Date(Long.valueOf(smsDate));
String type;
switch (Integer.parseInt(c.getString(c.getColumnIndexOrThrow(Telephony.Sms.TYPE)))) {
case Telephony.Sms.MESSAGE_TYPE_INBOX:
type = "inbox";
break;
case Telephony.Sms.MESSAGE_TYPE_SENT:
type = "sent";
break;
case Telephony.Sms.MESSAGE_TYPE_OUTBOX:
type = "outbox";
break;
default:
break;
}
c.moveToNext();
}
}
c.close();
} else {
Toast.makeText(this, "No message to show!", Toast.LENGTH_SHORT).show();
}
}
Make that "three single comment-markers"
In C# it's ///
which as default spits out:
/// <summary>
///
/// </summary>
/// <returns></returns>
You may use requests
library to find if website is up i.e. status code
as 200
import requests
url = "https://www.google.com"
page = requests.get(url)
print (page.status_code)
>> 200
try the following snippet
const renObjData = this.props.data.map(function(data, idx) {
return <ul key={idx}>{$.map(data,(val,ind) => {
return (<li>{val}</li>);
}
}</ul>;
});
While you are in debug mode within the catch {...}
block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:
((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors
This will allow you to drill down into the ValidationErrors
tree. It's the easiest way I've found to get instant insight into these errors.
For Visual 2012+ users who care only about the first error and might not have a catch
block, you can even do:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors.First().ValidationErrors.First().ErrorMessage
Demo: https://jsfiddle.net/kvxazhso/
Successfully pass equal values (keep same order). Flexible : handle ascendant (123) or descendant (321), works for numbers, letters, and unicodes. Works on all tested devices (Chrome, Android default browser, FF).
Given data such :
var people = [
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 3 },
{ 'myKey': 'C', 'status': 3 },
{ 'myKey': 'D', 'status': 2 },
{ 'myKey': 'E', 'status': 7 },
...
];
Sorting by ascending or reverse order:
function sortJSON(arr, key, way) {
return arr.sort(function(a, b) {
var x = a[key]; var y = b[key];
if (way === '123') { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }
if (way === '321') { return ((x > y) ? -1 : ((x < y) ? 1 : 0)); }
});
}
people2 = sortJSON(people,'status', '321'); // 123 or 321
alert("2. After processing (0 to x if 123; x to 0 if 321): "+JSON.stringify(people2));
java [any other JVM options you need to give it] -jar foo.jar
You can access the timezone by the following script:
SELECT * FROM pg_timezone_names WHERE name = current_setting('TIMEZONE');
output will be :
name- Europe/Berlin,
abbrev - CET,
utc_offset- 01:00:00,
is_dst- false
With layout_weight
you can specify a size ratio between multiple views. E.g. you have a MapView
and a table
which should show some additional information to the map. The map should use 3/4 of the screen and table should use 1/4 of the screen. Then you will set the layout_weight
of the map
to 3 and the layout_weight
of the table
to 1.
To get it work you also have to set the height or width (depending on your orientation) to 0px.
Try an OUTER APPLY
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
OUTER APPLY
(
SELECT TOP 1 *
FROM tbl_Media M
WHERE M.Content_Id = C.Content_Id
) m
ORDER BY
C.Content_DatePublished ASC
Alternatively, you could GROUP BY
the results
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id
GROUP BY
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
ORDER BY
C.Content_DatePublished ASC
The OUTER APPLY
selects a single row (or none) that matches each row from the left table.
The GROUP BY
performs the entire join, but then collapses the final result rows on the provided columns.
I was having the similar issue and solved by understanding the Classes in asp.net C#
I want to read following JSON string :
[
{
"resultList": [
{
"channelType": "",
"duration": "2:29:30",
"episodeno": 0,
"genre": "Drama",
"genreList": [
"Drama"
],
"genres": [
{
"personName": "Drama"
}
],
"id": 1204,
"language": "Hindi",
"name": "The Great Target",
"productId": 1204,
"productMasterId": 1203,
"productMasterName": "The Great Target",
"productName": "The Great Target",
"productTypeId": 1,
"productTypeName": "Movie",
"rating": 3,
"releaseyear": "2005",
"showGoodName": "Movies ",
"views": 8333
},
{
"channelType": "",
"duration": "2:30:30",
"episodeno": 0,
"genre": "Romance",
"genreList": [
"Romance"
],
"genres": [
{
"personName": "Romance"
}
],
"id": 1144,
"language": "Hindi",
"name": "Mere Sapnon Ki Rani",
"productId": 1144,
"productMasterId": 1143,
"productMasterName": "Mere Sapnon Ki Rani",
"productName": "Mere Sapnon Ki Rani",
"productTypeId": 1,
"productTypeName": "Movie",
"rating": 3,
"releaseyear": "1997",
"showGoodName": "Movies ",
"views": 6482
},
{
"channelType": "",
"duration": "2:34:07",
"episodeno": 0,
"genre": "Drama",
"genreList": [
"Drama"
],
"genres": [
{
"personName": "Drama"
}
],
"id": 1520,
"language": "Telugu",
"name": "Satyameva Jayathe",
"productId": 1520,
"productMasterId": 1519,
"productMasterName": "Satyameva Jayathe",
"productName": "Satyameva Jayathe",
"productTypeId": 1,
"productTypeName": "Movie",
"rating": 3,
"releaseyear": "2004",
"showGoodName": "Movies ",
"views": 9910
}
],
"resultSize": 1171,
"pageIndex": "1"
}
]
My asp.net c# code looks like following
First, Class3.cs page created in APP_Code folder of Web application
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;
/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{
public List<ListWrapper_Main> ResultList_Main { get; set; }
public class ListWrapper_Main
{
public List<ListWrapper> ResultList { get; set; }
public string resultSize { get; set; }
public string pageIndex { get; set; }
}
public class ListWrapper
{
public string channelType { get; set; }
public string duration { get; set; }
public int episodeno { get; set; }
public string genre { get; set; }
public string[] genreList { get; set; }
public List<genres_cls> genres { get; set; }
public int id { get; set; }
public string imageUrl { get; set; }
//public string imageurl { get; set; }
public string language { get; set; }
public string name { get; set; }
public int productId { get; set; }
public int productMasterId { get; set; }
public string productMasterName { get; set; }
public string productName { get; set; }
public int productTypeId { get; set; }
public string productTypeName { get; set; }
public decimal rating { get; set; }
public string releaseYear { get; set; }
//public string releaseyear { get; set; }
public string showGoodName { get; set; }
public string views { get; set; }
}
public class genres_cls
{
public string personName { get; set; }
}
}
Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data
JavaScriptSerializer ser = new JavaScriptSerializer();
string final_sb = sb.ToString();
List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());
foreach (var itemdetail in movieInfos)
{
foreach (var itemdetail2 in itemdetail.ResultList)
{
Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
Response.Write("duration=" + itemdetail2.duration + "<br/>");
Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
Response.Write("genre=" + itemdetail2.genre + "<br/>");
string[] genreList_arr = itemdetail2.genreList;
for (int i = 0; i < genreList_arr.Length; i++)
Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");
foreach (var genres1 in itemdetail2.genres)
{
Response.Write("genres1=" + genres1.personName + "<br>");
}
Response.Write("id=" + itemdetail2.id + "<br/>");
Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
//Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
Response.Write("language=" + itemdetail2.language + "<br/>");
Response.Write("name=" + itemdetail2.name + "<br/>");
Response.Write("productId=" + itemdetail2.productId + "<br/>");
Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
Response.Write("productName=" + itemdetail2.productName + "<br/>");
Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
Response.Write("rating=" + itemdetail2.rating + "<br/>");
Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
//Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
Response.Write("views=" + itemdetail2.views + "<br/><br>");
//Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
// Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");
}
Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");
}
'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply
This is basically - web application asp.net c# code....
N joy...
You can't. From the official tutorial:
By using the Class-Path header in the manifest, you can avoid having to specify a long -classpath flag when invoking Java to run the your application.
Note: The Class-Path header points to classes or JAR files on the local network, not JAR files within the JAR file or classes accessible over internet protocols. To load classes in JAR files within a JAR file into the class path, you must write custom code to load those classes. For example, if MyJar.jar contains another JAR file called MyUtils.jar, you cannot use the Class-Path header in MyJar.jar's manifest to load classes in MyUtils.jar into the class path.
You should use the location.reload(true)
, which will release the cache for that specific page and force the page to load as a NEW page.
The true
parameter forces the page to release it's cache.
I just changed availability date to a future date. After doing that, I received following message -
You have selected an Available Date in the future. This will remove your currently live version from the App Store until the new date. Changing Available Date affects all versions of the application, both Ready For Sale and In Review.
Which means that the app is removed and no longer available.
GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).
This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.
Only three lines of relevant code.
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
public class GsonFetchNetworkJson {
public static void main(String[] ignored) throws Exception {
URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyDto dto = new Gson().fromJson(reader, MyDto.class);
// using the deserialized object
System.out.println(dto.headers);
System.out.println(dto.args);
System.out.println(dto.origin);
System.out.println(dto.url);
}
private class MyDto {
Map<String, String> headers;
Map<String, String> args;
String origin;
String url;
}
}
If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with
curl
or other clients) then a possible cause could be that the endpoint expects aUser-Agent
header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g.System.setProperty("http.agent", "Netscape 1.0");
.
Sounds like you're doing this:
0..10.to_a
The warning is from Fixnum#to_a, not from Range#to_a. Try this instead:
(0..10).to_a
The problem is that if you try to write a <table>
or a <tr>
or <td>
tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.
Instead of writing your table line by line, concatenate your table into a variable and insert it once created:
<script language="javascript" type="text/javascript">
<!--
var myArray = new Array();
myArray[0] = 1;
myArray[1] = 2.218;
myArray[2] = 33;
myArray[3] = 114.94;
myArray[4] = 5;
myArray[5] = 33;
myArray[6] = 114.980;
myArray[7] = 5;
var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";
myTable+="<tr><td style='width: 100px; '>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td></tr>";
for (var i=0; i<8; i++) {
myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
myArray[i] = myArray[i].toFixed(3);
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
}
myTable+="</table>";
document.write( myTable);
//-->
</script>
If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:
<div id="tablePrint"> </div>
And in JS instead of document.write(myTable)
use the following code:
document.getElementById('tablePrint').innerHTML = myTable;
The following is simple and works on SQL Server 2008 (SP3) and up:
PRINT @@VERSION
PRINT GETDATE()
PRINT GETDATE() + '01:00:00'
PRINT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE()))) + '01:00:00'
With output:
Microsoft SQL Server 2008 (SP3) - 10.0.5500.0 (X64)
Mar 15 2017 6:17PM
Mar 15 2017 7:17PM
Mar 15 2017 1:00AM
I needed a progress bar for iterating over the lines in a csv file. Was able to adapt cprn's code into something useful for me:
BAR='##############################'
FILL='------------------------------'
totalLines=$(wc -l $file | awk '{print $1}') # num. lines in file
barLen=30
# --- iterate over lines in csv file ---
count=0
while IFS=, read -r _ col1 col2 col3; do
# update progress bar
count=$(($count + 1))
percent=$((($count * 100 / $totalLines * 100) / 100))
i=$(($percent * $barLen / 100))
echo -ne "\r[${BAR:0:$i}${FILL:$i:barLen}] $count/$totalLines ($percent%)"
# other stuff
(...)
done <$file
Looks like this:
[##----------------------------] 17128/218210 (7%)
There is an hard limit on how much data can be stored in a single row of a mysql table, regardless of the number of columns or the individual column length.
As stated in the OFFICIAL DOCUMENTATION
The maximum row size constrains the number (and possibly size) of columns because the total length of all columns cannot exceed this size. For example, utf8 characters require up to three bytes per character, so for a CHAR(255) CHARACTER SET utf8 column, the server must allocate 255 × 3 = 765 bytes per value. Consequently, a table cannot contain more than 65,535 / 765 = 85 such columns.
Storage for variable-length columns includes length bytes, which are assessed against the row size. For example, a VARCHAR(255) CHARACTER SET utf8 column takes two bytes to store the length of the value, so each value can take up to 767 bytes.
Here you can find INNODB TABLES LIMITATIONS
if you had only one field to "DISTINCT", you could use:
SELECT COUNT(DISTINCT DocumentId)
FROM DocumentOutputItems
and that does return the same query plan as the original, as tested with SET SHOWPLAN_ALL ON. However you are using two fields so you could try something crazy like:
SELECT COUNT(DISTINCT convert(varchar(15),DocumentId)+'|~|'+convert(varchar(15), DocumentSessionId))
FROM DocumentOutputItems
but you'll have issues if NULLs are involved. I'd just stick with the original query.
Given your representation, your function is as efficient as can be done. Of course, as noted by others (and as practiced in languages older than Lua), the solution to your real problem is to change representation. When you have tables and you want sets, you turn tables into sets by using the set element as the key and true
as the value. +1 to interjay.
forever module has a concept of multiple node.js servers, and can start, restart, stop and list currently running servers. It can also watch for changing files and restart node as needed.
Install it if you don't have it already:
npm install forever -g
After installing it, call the forever
command: use the -w
flag to watch file for changes:
forever -w ./my-script.js
In addition, you can watch directory and ignore patterns:
forever --watch --watchDirectory ./path/to/dir --watchIgnore *.log ./start/file
Another advantage of CXF: it connects to web servers using NTLMV2 authentication out of the box. (used by Windows 2008 & up) Before using CXF, I hacked Axis2 to use HTTPClient V4 + JCIFS to make this possible.
Found out that there's no bug there. Just add:
<base href="/" />
to your <head />
.
In WAMP, right click on WAMP tray icon then change the port from 3308 to 3306 like this:
Android Studio 3.5.3 It works with this configuration.
I found this framework: jensoft sw2d, free for non commercial use (dual licensing)
regards.
This problem normally appears while copy pasting the tag lib URL from the internet. Usually the quotes ""
in which the URL http://www.springframework.org/tags is embedded might not be correct. Try removing quotes and type them manually. This resolved the issue for me.
$(document).ready(function () {
$("#divId").toggleClass('cssclassname'); // toggle class
});
**OR**
$(document).ready(function() {
$("#objectId").click(function() { // click or other event to change the div class
$("#divId").toggleClass("cssclassname"); // toggle class
)};
)};
Maybe you're not doing it as root?
Try sudo nginx -s reload
, if it still doesn't work, you might want to try sudo pkill -HUP nginx
.
app.run(['$window', '$rootScope',
function ($window , $rootScope) {
$rootScope.goBack = function(){
$window.history.back();
}
}]);
<a href="#" ng-click="goBack()">Back</a>
By default Bundler will check your system first and if it can't find a gem it will use the sources specified in your Gemfile.
You can probably start a Service
here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.
UDPATE
You can use START_STICKY
to make your Service running continuously.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
This is the solution I came up with:
import time
from threading import Thread
from threading import Lock
def myfunc(i, mutex):
mutex.acquire(1)
time.sleep(1)
print "Thread: %d" %i
mutex.release()
mutex = Lock()
for i in range(0,10):
t = Thread(target=myfunc, args=(i,mutex))
t.start()
print "main loop %d" %i
Output:
main loop 0
main loop 1
main loop 2
main loop 3
main loop 4
main loop 5
main loop 6
main loop 7
main loop 8
main loop 9
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
If you don't want to place the watch inside a specific controller, you can add the watch for the whole aplication in Angular app run()
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
// handle route changes
});
});
https://stackoverflow.com/a/9824943/14731 contains a better answer (one that is more readable and works with set -o nounset
enabled). It works roughly like this:
if [ -n "${VAR-}" ]; then
echo "VAR is set and is not empty"
elif [ "${VAR+DEFINED_BUT_EMPTY}" = "DEFINED_BUT_EMPTY" ]; then
echo "VAR is set, but empty"
else
echo "VAR is not set"
fi
One-line numpy solution for downsampling (by 2):
smaller_img = bigger_img[::2, ::2]
And upsampling (by 2):
bigger_img = smaller_img.repeat(2, axis=0).repeat(2, axis=1)
(this asssumes HxWxC shaped image. h/t to L. Kärkkäinen in the comments above. note this method only allows whole integer resizing (e.g., 2x but not 1.5x))
Did you try passwd -d root
? Most likely, this will do what you want.
You can also manually edit /etc/shadow
: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to
root:$X$SK5xfLB1ZW:0:0...
There, delete the second field (everything between the first and second colon):
root::0:0...
Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)
root:*:0:0...
Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d
, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd
, and use mkpasswd
to create the second field for the /etc/shadow.)
String str = "Your string";
byte[] array = str.getBytes();
@jordanstephens said this in a comment, but it kind of gets lost and was a really easy fix for me.
I simply added HEAD method and clicked saved and it started working.
<CORSConfiguration>_x000D_
<CORSRule>_x000D_
<AllowedOrigin>*</AllowedOrigin>_x000D_
<AllowedMethod>GET</AllowedMethod>_x000D_
<AllowedMethod>HEAD</AllowedMethod> <!-- Add this -->_x000D_
<MaxAgeSeconds>3000</MaxAgeSeconds>_x000D_
<AllowedHeader>Authorization</AllowedHeader>_x000D_
</CORSRule>_x000D_
</CORSConfiguration>
_x000D_
I found this article that provided a solution for me. It pertains to Xcode 7 where the default for No Common Blocks is Yes rather than No in previous versions.
This is a quote from the article:
The problem seems to be that the "No common blocks" in the "Apple LLVM 6.1 - Code Generation" section in the Build settings pane is set to Yes, in the latest version of Xcode.
This caused what I will describe as circular references where a class that was included in my Compile Sources was referenced via a #import in another source file (appDelegate.m). This caused duplicate blocks for variables that were declared in the original base class.
Changing the value to No immediately enabled my app to compile and resolved my problem.
You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:
if ([category isEqualToString:@"Some String"])
{
// Both strings are equal without respect to their case.
}
Case-insensitive is like this:
if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
// Both strings are equal with respect to their case.
}
I think if you want to add content directly to the body, the best way is:
document.body.innerHTML = document.body.innerHTML + "bla bla";
To replace it, use:
document.body.innerHTML = "bla bla";
If You want to have a reference to this variable across the whole project, create somewhere d.ts
file, e.g. globals.d.ts
. Fill it with your global variables declarations, e.g.:
declare const BootBox: 'boot' | 'box';
Now you can reference it anywhere across the project, just like that:
const bootbox = BootBox;
Here's an example.
Pandas supports NumPy syntax which allows:
df[len(df) -1:].index[0]
Nested fragments are supported in android 4.2 and later
The Android Support Library also now supports nested fragments, so you can implement nested fragment designs on Android 1.6 and higher.
To nest a fragment, simply call getChildFragmentManager() on the Fragment in which you want to add a fragment. This returns a FragmentManager that you can use like you normally do from the top-level activity to create fragment transactions. For example, here’s some code that adds a fragment from within an existing Fragment class:
Fragment videoFragment = new VideoPlayerFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.video_fragment, videoFragment).commit();
To get more idea about nested fragments, please go through these tutorials
Part 1
Part 2
Part 3
and here is a SO post which discuss about best practices for nested fragments.
Here's a function that uses .NET's System.IO
classes directly:
function GetLineAt([String] $path, [Int32] $index)
{
[System.IO.FileMode] $mode = [System.IO.FileMode]::Open;
[System.IO.FileAccess] $access = [System.IO.FileAccess]::Read;
[System.IO.FileShare] $share = [System.IO.FileShare]::Read;
[Int32] $bufferSize = 16 * 1024;
[System.IO.FileOptions] $options = [System.IO.FileOptions]::SequentialScan;
[System.Text.Encoding] $defaultEncoding = [System.Text.Encoding]::UTF8;
# FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions) constructor
# http://msdn.microsoft.com/library/d0y914c5.aspx
[System.IO.FileStream] $input = New-Object `
-TypeName 'System.IO.FileStream' `
-ArgumentList ($path, $mode, $access, $share, $bufferSize, $options);
# StreamReader(Stream, Encoding, Boolean, Int32) constructor
# http://msdn.microsoft.com/library/ms143458.aspx
[System.IO.StreamReader] $reader = New-Object `
-TypeName 'System.IO.StreamReader' `
-ArgumentList ($input, $defaultEncoding, $true, $bufferSize);
[String] $line = $null;
[Int32] $currentIndex = 0;
try
{
while (($line = $reader.ReadLine()) -ne $null)
{
if ($currentIndex++ -eq $index)
{
return $line;
}
}
}
finally
{
# Close $reader and $input
$reader.Close();
}
# There are less than ($index + 1) lines in the file
return $null;
}
GetLineAt 'file.txt' 9;
Tweaking the $bufferSize
variable might affect performance. A more concise version that uses default buffer sizes and doesn't provide optimization hints could look like this:
function GetLineAt([String] $path, [Int32] $index)
{
# StreamReader(String, Boolean) constructor
# http://msdn.microsoft.com/library/9y86s1a9.aspx
[System.IO.StreamReader] $reader = New-Object `
-TypeName 'System.IO.StreamReader' `
-ArgumentList ($path, $true);
[String] $line = $null;
[Int32] $currentIndex = 0;
try
{
while (($line = $reader.ReadLine()) -ne $null)
{
if ($currentIndex++ -eq $index)
{
return $line;
}
}
}
finally
{
$reader.Close();
}
# There are less than ($index + 1) lines in the file
return $null;
}
GetLineAt 'file.txt' 9;
easier & shorter via indirect: INDIRECT("'..\..\..\..\Supply\SU\SU.ods'#$Data.$A$2:$AC$200")
however indirect() has performance drawbacks if lot of links in workbook
I miss construct like: ['../Data.ods']#Sheet1.A1
in LibreOffice. The intention is here: if I create a bunch of master workbooks and depending report workbooks in limited subtree of directories in source file system, I can zip whole directory subtree with complete package of workbooks and send it to other cooperating person per Email or so. It will be saved in some other absolute pazth on target system, but linkage works again in new absolute path because it was coded relatively to subtree root.
params
is for GET-style URL parameters, data
is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.
Your raw post contains JSON data though. requests
can handle JSON encoding for you, and it'll set the correct Content-Type
header too; all you need to do is pass in the Python object to be encoded as JSON into the json
keyword argument.
You could split out the URL parameters as well:
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
then post your data with:
import requests
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, json=data)
The json
keyword is new in requests
version 2.4.2; if you still have to use an older version, encode the JSON manually using the json
module and post the encoded result as the data
key; you will have to explicitly set the Content-Type header in that case:
import requests
import json
headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, data=json.dumps(data), headers=headers)
Here's how to make your very own cls
or clear
command that will work without explicitly calling any function!
We'll take advantage of the fact that the python console calls repr()
to display objects on screen. This is especially useful if you have your own customized python shell (with the -i
option for example) and you have a pre-loading script for it. This is what you need:
import os
class ScreenCleaner:
def __repr__(self):
os.system('cls') # This actually clears the screen
return '' # Because that's what repr() likes
cls = ScreenCleaner()
Use clear
instead of cls
if you're on linux (in both the os
command and the variable name)!
Now if you just write cls
or clear
in the console - it will clear it! Not even cls()
or clear()
- just the raw variable. This is because python will call repr(cls)
to print it out, which will in turn trigger our __repr__
function.
Let's test it out:
>>> df;sag
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'df' is not defined
>>> sglknas
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sglknas' is not defined
>>> lksnldn
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'lksnldn' is not defined
>>> cls
And the screen is clear!
To clarify - the code above needs to either be imported in the console like this
from somefile import cls
Or pre load directly with something like:
python -i my_pre_loaded_classes.py
Set Arg = WScript.Arguments
set WshShell = createObject("Wscript.Shell")
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
Set rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append "LineNumber", 4
.Fields.Append "Txt", 201, 5000
.Open
LineCount = 0
Do Until Inp.AtEndOfStream
LineCount = LineCount + 1
.AddNew
.Fields("LineNumber").value = LineCount
.Fields("Txt").value = Inp.readline
.UpDate
Loop
.Sort = "LineNumber ASC"
If LCase(Arg(1)) = "t" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber < " & LCase(Arg(3)) + 1
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber > " & LCase(Arg(3))
End If
ElseIf LCase(Arg(1)) = "b" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber > " & LineCount - LCase(Arg(3))
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber < " & LineCount - LCase(Arg(3)) + 1
End If
End If
Do While not .EOF
Outp.writeline .Fields("Txt").Value
.MoveNext
Loop
End With
Cut
filter cut {t|b} {i|x} NumOfLines
Cuts the number of lines from the top or bottom of file.
t - top of the file
b - bottom of the file
i - include n lines
x - exclude n lines
Example
cscript /nologo filter.vbs cut t i 5 < "%systemroot%\win.ini"
Another way This outputs lines 5001+, adapt for your use. This uses almost no memory.
Do Until Inp.AtEndOfStream
Count = Count + 1
If count > 5000 then
OutP.WriteLine Inp.Readline
End If
Loop
Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.
but what's the deal with new lines and carriage returns? What's the difference? Is \n\n the equivalent of \r\r or \n\r? Which should I use when I'm creating a line gap between lines?
No one here seemed to actualy answer this question, so here I am.
\r
represents 'carriage-return'
\n
represents 'line-feed'
The actual reason for them goes back to typewriters. As you typed the 'carriage' would slowly slide, character by character, to the right of the typewriter. When you got to the end of the line you would return the carriage and then go to a new line. To go to the new line, you would flip a lever which fed the lines to the type writer. Thus these actions, combined, were called carriage return line feed. So quite literally:
A line feed,\n
, means moving to the next line.
A carriage return, \r
, means moving the cursor to the beginning of the line.
Ultimately Hello\n\nWorld
should result in the following output on the screen:
Hello
World
Where as Hello\r\rWorld
should result in the following output.
It's only when combining the 2 characters \r\n
that you have the common understanding of knew line. I.E. Hello\r\nWorld
should result in:
Hello
World
And of course \n\r
would result in the same visual output as \r\n
.
Originally computers took \r
and \n
quite literally. However these days the support for carriage return is sparse. Usually on every system you can get away with using \n
on its own. It never depends on the OS, but it does depend on what you're viewing the output in.
Still I'd always advise using \r\n
wherever you can!
This work for me when I wanted to show a photo depending on the gender of the user:
<img th:src="${generou}=='Femenino' ? @{/images/user_mujer.jpg}: @{/images/user.jpg}" alt="AdminLTE Logo" class="brand-image img-circle elevation-3">
tr:hover td.someclass {
background: #EDB01C;
color:#FFF;
}
only someclass cell highlight
To check input type
<!DOCTYPE html>
<html>
<body>
<input type=number id="txtinp">
<button onclick=checktype()>Try it</button>
<script>
function checktype()
{
alert(document.getElementById("txtinp").type);
}
</script>
</body>
</html>
Swift 2.0 version of jungledev's answer
func getTopViewController() -> UIViewController {
var topViewController = UIApplication.sharedApplication().delegate!.window!!.rootViewController!
while (topViewController.presentedViewController != nil) {
topViewController = topViewController.presentedViewController!
}
return topViewController
}
I used PathFindExtension() function to know whether it is a valid tif file or not.
#include <Shlwapi.h>
bool A2iAWrapperUtility::isValidImageFile(string imageFile)
{
char * pStrExtension = ::PathFindExtension(imageFile.c_str());
if (pStrExtension != NULL && strcmp(pStrExtension, ".tif") == 0)
{
return true;
}
return false;
}
One of the difference is that merge
is creating a new index, and join
is keeping the left side index. It can have a big consequence on your later transformations if you wrongly assume that your index isn't changed with merge
.
For example:
import pandas as pd
df1 = pd.DataFrame({'org_index': [101, 102, 103, 104],
'date': [201801, 201801, 201802, 201802],
'val': [1, 2, 3, 4]}, index=[101, 102, 103, 104])
df1
date org_index val
101 201801 101 1
102 201801 102 2
103 201802 103 3
104 201802 104 4
-
df2 = pd.DataFrame({'date': [201801, 201802], 'dateval': ['A', 'B']}).set_index('date')
df2
dateval
date
201801 A
201802 B
-
df1.merge(df2, on='date')
date org_index val dateval
0 201801 101 1 A
1 201801 102 2 A
2 201802 103 3 B
3 201802 104 4 B
-
df1.join(df2, on='date')
date org_index val dateval
101 201801 101 1 A
102 201801 102 2 A
103 201802 103 3 B
104 201802 104 4 B
If you just want to get the information of current directory, you can type:
pwd
and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.
yes there is. it is called corona sdk!
This solution worked for me.
function isset(object){
return (typeof object !=='undefined');
}
Upgrade pip as follows:
curl https://bootstrap.pypa.io/get-pip.py | python
Note: You may need to use sudo python
above if not in a virtual environment.
Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.
(Note that upgrading pip via pip install --upgrade pip
will also not upgrade it correctly. It is a chicken-and-egg issue)
This thread explains it (thanks to this Twitter post):
Mac users who use pip and PyPI:
If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:
curl https://bootstrap.pypa.io/get-pip.py | python
and we recommend you do that by April 8th.
Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/
Also, the Python status page:
Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC
Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC
Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:
pip install --upgrade setuptools
The two commands have the same effect (thanks to Robert Siemer’s answer for pointing it out).
The practical difference comes when using a local branch named differently:
git checkout -b mybranch origin/abranch
will create mybranch
and track origin/abranch
git checkout --track origin/abranch
will only create 'abranch
', not a branch with a different name.(That is, as commented by Sebastian Graf, if the local branch did not exist already.
If it did, you would need git checkout -B abranch origin/abranch
)
Note: with Git 2.23 (Q3 2019), that would use the new command git switch
:
git switch -c <branch> --track <remote>/<branch>
If the branch exists in multiple remotes and one of them is named by the
checkout.defaultRemote
configuration variable, we'll use that one for the purposes of disambiguation, even if the<branch>
isn't unique across all remotes.
Set it to e.g.checkout.defaultRemote=origin
to always checkout remote branches from there if<branch>
is ambiguous but exists on the 'origin' remote.
Here, '-c
' is the new '-b
'.
First, some background: Tracking means that a local branch has its upstream set to a remote branch:
# git config branch.<branch-name>.remote origin
# git config branch.<branch-name>.merge refs/heads/branch
git checkout -b branch origin/branch
will:
branch
to the point referenced by origin/branch
.branch
(with git branch
) and track the remote tracking branch origin/branch
. When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the
branch.<name>.remote
andbranch.<name>.merge
configuration entries) so thatgit pull
will appropriately merge from the remote-tracking branch.
This behavior may be changed via the globalbranch.autosetupmerge
configuration flag. That setting can be overridden by using the--track
and--no-track
options, and changed later using git branch--set-upstream-to
.
And git checkout --track origin/branch
will do the same as git branch --set-upstream-to
):
# or, since 1.7.0
git branch --set-upstream upstream/branch branch
# or, since 1.8.0 (October 2012)
git branch --set-upstream-to upstream/branch branch
# the short version remains the same:
git branch -u upstream/branch branch
It would also set the upstream for 'branch
'.
(Note: git1.8.0 will deprecate git branch --set-upstream
and replace it with git branch -u|--set-upstream-to
: see git1.8.0-rc1 announce)
Having an upstream branch registered for a local branch will:
git status
and git branch -v
. git pull
without arguments to pull from the upstream when the new branch is checked out.See "How do you make an existing git branch track a remote branch?" for more.
Window -> Preferences -> C/C++ -> Build -> Console
On Limit Console output field increase a desired number of lines.
VistaDB is the only alternative if you going to run your website at shared hosting (almost all of them won't let you run your websites under Full Trust mode) and also if you need simple x-copy deployment enabled website.
It is not necessary to change java as a String parameter. You have to change the c code to receive a String without a pointer and in its code:
Bool DmgrGetVersion (String szVersion);
Char NewszVersion [200];
Strcpy (NewszVersion, szVersion.t_str ());
.t_str () applies to builder c ++ 2010
You have 2 issues here.
use ==
for comparison. You've used =
which is for assignment.
use &&
for "and" and ||
for "or". and
and or
will work but they are unconventional.
Just use window.open()
function? The third parameter lets you specify window size.
var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
var URL = "https://www.linkedin.com/cws/share?mini=true&url=" + location.href;
var win = window.open(URL, "_blank", strWindowFeatures);
It depends on what you mean by stop. If it's in a function that can return void then:
if(a && b) {
// do something
}else{
// "stop"
return;
}
Use the System.getenv(String)
method, passing the name of the variable to read.
Yes, you can use the ALTER TABLE t AUTO_INCREMENT = 42
statement. However, you need to be aware that this will cause the rebuilding of your entire table, at least with InnoDB and certain MySQL versions. If you have an already existing dataset with millions of rows, it could take a very long time to complete.
In my experience, it's better to do the following:
BEGIN WORK;
-- You may also need to add other mandatory columns and values
INSERT INTO t (id) VALUES (42);
ROLLBACK;
In this way, even if you're rolling back the transaction, MySQL will keep the auto-increment value, and the change will be applied instantly.
You can verify this by issuing a SHOW CREATE TABLE t
statement. You should see:
> SHOW CREATE TABLE t \G
*************************** 1. row ***************************
Table: t
Create Table: CREATE TABLE `t` (
...
) ENGINE=InnoDB AUTO_INCREMENT=43 ...
I fixed similar issues by qutating column name
SELECT * from table_name where "foo" is NULL;
In my case it was just
SELECT id, "foo" from table_name;
without quotes i'v got same error.
Just a note for php developers (I lack the necessary stackoverflow points to post this as a comment) ... the automagic (and silent) conversion to TINYINT means that php retrieves a value from a "BOOLEAN" column as a "0" or "1", not the expected (by me) true/false.
A developer who is looking at the SQL used to create a table and sees something like: "some_boolean BOOLEAN NOT NULL DEFAULT FALSE," might reasonably expect to see true/false results when a row containing that column is retrieved. Instead (at least in my version of PHP), the result will be "0" or "1" (yes, a string "0" or string "1", not an int 0/1, thank you php).
It's a nit, but enough to cause unit tests to fail.
I use easy_install with Apple's Python, and it works like a charm.
Yep, using the staticmethod decorator
class MyClass(object):
@staticmethod
def the_static_method(x):
print(x)
MyClass.the_static_method(2) # outputs 2
Note that some code might use the old method of defining a static method, using staticmethod
as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)
class MyClass(object):
def the_static_method(x):
print(x)
the_static_method = staticmethod(the_static_method)
MyClass.the_static_method(2) # outputs 2
This is entirely identical to the first example (using @staticmethod
), just not using the nice decorator syntax
Finally, use staticmethod
sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.
The following is verbatim from the documentation::
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C: @staticmethod def f(arg1, arg2, ...): ...
The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.
It can be called either on the class (such as
C.f()
) or on an instance (such asC().f()
). The instance is ignored except for its class.Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see
classmethod()
.For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.
New in version 2.2.
Changed in version 2.4: Function decorator syntax added.
I would use XMLHTTP request to retrieve page content as much faster. Then it is easy enough to use querySelectorAll to apply a CSS class selector to grab by class name. Then you access the child elements by tag name and index.
Option Explicit
Public Sub GetInfo()
Dim sResponse As String, html As HTMLDocument, elements As Object, i As Long
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://www.hsbc.com/about-hsbc/leadership", False
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
.send
sResponse = StrConv(.responseBody, vbUnicode)
End With
Set html = New HTMLDocument
With html
.body.innerHTML = sResponse
Set elements = .querySelectorAll(".profile-col1")
For i = 0 To elements.Length - 1
Debug.Print String(20, Chr$(61))
Debug.Print elements.item(i).getElementsByTagName("a")(0).innerText
Debug.Print elements.item(i).getElementsByTagName("p")(0).innerText
Debug.Print elements.item(i).getElementsByTagName("p")(1).innerText
Next
End With
End Sub
References:
VBE > Tools > References > Microsoft HTML Object Library
The '\r'
character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.
From the old telnet specification (RFC 854) (page 11):
The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").
However, from the latest specification (RFC5198) (page 13):
...
In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.
LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).
So newline in Telnet should always be '\r\n'
but most implementations have either not been updated, or keeps the old '\n\r'
for backwards compatibility.
This works in Chrome, Firefox, doesn't work in Safari :(, haven't tested in other browsers
delete window.document.referrer;
window.document.__defineGetter__('referrer', function () {
return "yoururl.com";
});
Saw that here https://gist.github.com/papoms/3481673
Regards
test case: https://jsfiddle.net/bez3w4ko/ (so you can easily test several browsers) and here is a test with iframes https://jsfiddle.net/2vbfpjp1/1/
Your web form should look like this:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebUI._Default" MasterPageFile="~/Site1.Master" %>
<asp:Content runat="server" ID="head" ContentPlaceHolderId="head">
<!-- stuff you want in >head%lt; -->
</asp:Content>
<asp:Content runat="server" ID="content" ContentPlaceHolderId="ContentPlaceHolder1">
<h1>Your content</h1>
</asp:Content>
Note that there is no <html>
tag
I don't have enough reputation to comment, but this is referring to dsissitka's answer. It works on Windows 10 as well.
To reiterate, the commands are:
cd (App Dir)
react-native start > /dev/null 2>&1 &
adb reverse tcp:8081 tcp:8081
The -jar option is mutually exclusive of -classpath. See an old description here
-jar
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.
See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.
A quick and dirty hack is to append your classpath to the bootstrap classpath:
-Xbootclasspath/a:path
Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.
However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.
I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.
There is no way to elegantly handle integer-based enumerated types. You might think of using a string-based enumeration instead of your solution. Not a preferred way all the times, but it still exists.
public enum Port {
/**
* The default port for the push server.
*/
DEFAULT("443"),
/**
* The alternative port that can be used to bypass firewall checks
* made to the default <i>HTTPS</i> port.
*/
ALTERNATIVE("2197");
private final String portString;
Port(final String portString) {
this.portString = portString;
}
/**
* Returns the port for given {@link Port} enumeration value.
* @return The port of the push server host.
*/
public Integer toInteger() {
return Integer.parseInt(portString);
}
}
try this:
<a id="send-thoughts" href="">Click</a>
<textarea id="message"></textarea>
<!--<textarea id="#message"></textarea>-->
jQuery("a#send-thoughts").click(function() {
//var thought = jQuery("textarea#message").val();
var thought = $("#message").val();
alert(thought);
});
If you only want to hide the search form for example because you have column input filters or may be because you already have a CMS search form able to return results from the table then all you have to do is inspect the form and get its id - (at the time of writing this, it looks as such[tableid]-table_filter.dataTables_filter
). Then simply do [tableid]-table_filter.dataTables_filter{display:none;}
retaining all other features of datatables.
If you want to stash untracked files, but keep indexed files (the ones you're about to commit for example), just add -k
(keep index) option to the -u
git stash -u -k
You may want to take a look at this question: Asynchronous IO in Java?
It looks like your best bet, if you don't want to wrangle the threads yourself is a framework. The previous post mentions Grizzly, https://grizzly.dev.java.net/, and Netty, http://www.jboss.org/netty/.
From the netty docs:
The Netty project is an effort to provide an asynchronous event-driven network application framework and tools for rapid development of maintainable high performance & high scalability protocol servers & clients.
As per my understanding you want data in dictionary as shown below:
key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3
for this you can use list for each dictionary keys:
case_list = {}
for entry in entries_list:
if key in case_list:
case_list[key1].append(value)
else:
case_list[key1] = [value]
if you use jquery on you website, you can use something like this your console
$.post(_x000D_
'dom/data-home.php',_x000D_
{_x000D_
type : "home", id : "0"_x000D_
},function(data){_x000D_
console.log(data)_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
_x000D_
This download fixed my VB6 EXE and Access 2016 (using ACEDAO.DLL) run-time error 429. Took me 2 long days to get it resolved because there are so many causes of 429.
http://www.microsoft.com/en-ca/download/details.aspx?id=13255
QUOTE from link: "This download will install a set of components that can be used to facilitate transfer of data between 2010 Microsoft Office System files and non-Microsoft Office applications"
using jquery $.each
you can access all data and also set in table like this
<table style="width: 100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Category</th>
<th>Color</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
$.each(data, function (index, item) {
var eachrow = "<tr>"
+ "<td>" + item[1] + "</td>"
+ "<td>" + item[2] + "</td>"
+ "<td>" + item[3] + "</td>"
+ "<td>" + item[4] + "</td>"
+ "</tr>";
$('#tbody').append(eachrow);
});
Another way could be as follows:-
#extracting numeric columns from iris datset
(iris[sapply(iris, is.numeric)])
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);
its going to give you solution i suppose
Just as most have said, but dont forget to set LifeCycleOwner
Sample in Java
i.e
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
BindingClass binding = DataBindingUtil.inflate(inflater, R.layout.fragment_layout, container, false);
ModelClass model = ViewModelProviders.of(getActivity()).get(ViewModelClass.class);
binding.setLifecycleOwner(getActivity());
binding.setViewmodelclass(model);
//Your codes here
return binding.getRoot();
}
Here is what I do to remove the validate password plugin:
mysql -h localhost -u root -p
uninstall plugin validate_password;
UNINSTALL COMPONENT 'file://component_validate_password';
I would not recommend this solution for a production system. I used this solution on a local mysql instance for development purposes only.
When I'm just testing a string to see if it is a GUID, I don't really want to create a Guid object that I don't need. So...
public static class GuidEx
{
public static bool IsGuid(string value)
{
Guid x;
return Guid.TryParse(value, out x);
}
}
And here's how you use it:
string testMe = "not a guid";
if (GuidEx.IsGuid(testMe))
{
...
}
Try this function...
function calculate_age(birth_month,birth_day,birth_year)
{
today_date = new Date();
today_year = today_date.getFullYear();
today_month = today_date.getMonth();
today_day = today_date.getDate();
age = today_year - birth_year;
if ( today_month < (birth_month - 1))
{
age--;
}
if (((birth_month - 1) == today_month) && (today_day < birth_day))
{
age--;
}
return age;
}
OR
function getAge(dateString)
{
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
{
age--;
}
return age;
}
I found this table super useful for deciding when to use different types of Contexts:
Original article here.
After several attempts and going deep in Tomcat's source code I found out that the simple property useNaming="false" did the trick!! Now Tomcat resolves names java:/liferay instead of java:comp/env/liferay
I had the same message with a totally different cause: the wsock32.dll
was not found. The ::socket(PF_INET, SOCK_STREAM, 0);
call kept returning an INVALID_SOCKET
but the reason was that the winsock dll was not loaded.
In the end I launched Sysinternals' process monitor and noticed that it searched for the dll 'everywhere' but didn't find it.
Silent failures are great!
if your wanting to use jQuery for this, try the following code.
$('select option[value="1"]').attr("selected",true);
Updated:
Following a comment from Vivek, correctly pointed out steven spielberg wanted to select the option via its Text value.
Here below is the updated code.
$('select option:contains("it\'s me")').prop('selected',true);
You need to use the :contains(text)
selector to find via the containing text.
Also jQuery prop offeres better support for Internet Explorer when getting and setting attributes.
If you used managed wordpress or caching plugins, you have to CLEAR YOUR CACHE before the facebook debugger tool can fetch new info!
I've been pulling my hair out for weeks figuring out why changes I made wouldn't show up in facebook debugger for 24 hours!!!! The fix is I have to go into my wordpress dashboard, click the godaddy icon on the top, and click "flush cache." I think many managed wordpress hosters have a cache to figure out how to clear it and you'll be golden.
What I did in my Swift project
1: Create new Swift File
2: Create a struct and static constant in it.
3: For Using just use YourStructName.baseURL
Note: After Creating initialisation takes little time so it will show in other viewcontrollers after 2-5 seconds.
import Foundation
struct YourStructName {
static let MerchantID = "XXX"
static let MerchantUsername = "XXXXX"
static let ImageBaseURL = "XXXXXXX"
static let baseURL = "XXXXXXX"
}
As for the meaning of each character described in C Primer Plus, what you expected is an 'correct' answer. It should be true for some computer architectures and compilers, but unfortunately not yours.
I wrote a simple c program to repeat your test, and got that 'correct' answer. I was using Mac OS and gcc.
Also, I am very curious what is the compiler that you were using. :)
In Swift 4 You can use
->Go Info.plist
-> Click plus of Information properties list
->Add App Transport Security Settings as dictionary
-> Click Plus icon App Transport Security Settings
-> Add Allow Arbitrary Loads set YES
Bellow image look like
Beyond historical (good and already reported) reasons, there's is also a little problem with operators precedence: dot operator has higher priority than star operator, so if you have struct containing pointer to struct containing pointer to struct... These two are equivalent:
(*(*(*a).b).c).d
a->b->c->d
But the second is clearly more readable. Arrow operator has the highest priority (just as dot) and associates left to right. I think this is clearer than use dot operator both for pointers to struct and struct, because we know the type from the expression without have to look at the declaration, that could even be in another file.
Updated using look-behind support in line with ECMAScript2018 changes.
For backwards compatibility, scroll further down to see the original solution.
A regular expression may be used - notably useful in dealing with big numbers stored as strings.
const format = num => _x000D_
String(num).replace(/(?<!\..*)(\d)(?=(?:\d{3})+(?:\.|$))/g, '$1,')_x000D_
_x000D_
;[_x000D_
format(100), // "100"_x000D_
format(1000), // "1,000"_x000D_
format(1e10), // "10,000,000,000" _x000D_
format(1000.001001), // "1,000.001001"_x000D_
format('100000000000000.001001001001') // "100,000,000,000,000.001001001001_x000D_
]_x000D_
.forEach(n => console.log(n))
_x000D_
» Verbose regex explanation (regex101.com)
This original answer may not be required but can be used for backwards compatibility.
Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here's another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.
const format = num => {_x000D_
const n = String(num),_x000D_
p = n.indexOf('.')_x000D_
return n.replace(_x000D_
/\d(?=(?:\d{3})+(?:\.|$))/g,_x000D_
(m, i) => p < 0 || i < p ? `${m},` : m_x000D_
)_x000D_
}_x000D_
_x000D_
;[_x000D_
format(100), // "100"_x000D_
format(1000), // "1,000"_x000D_
format(1e10), // "10,000,000,000" _x000D_
format(1000.001001), // "1,000.001001"_x000D_
format('100000000000000.001001001001') // "100,000,000,000,000.001001001001_x000D_
]_x000D_
.forEach(n => console.log(n))
_x000D_
If you are using a strongly-typed dataset then you should do this:
If Not ediTransactionRow.Ispay_id1Null Then
'Do processing here
End If
You are getting the error because a strongly-typed data set retrieves the underlying value and exposes the conversion through the property. For instance, here is essentially what is happening:
Public Property pay_Id1 Then
Get
return DirectCast(me.GetValue("pay_Id1", short)
End Get
'Abbreviated for clarity
End Property
The GetValue method is returning DBNull which cannot be converted to a short.
This worked for me:
<button #loginButton ...
and inside the controller:
@ViewChild('loginButton') loginButton;
...
this.loginButton.getNativeElement().click();
You can use the -R option to find the files along with those inside the recursive directories
ls -R | wc -l // to find all the files
ls -R | grep log | wc -l // to find the files which contains the word log
you can use patterns on the grep
If you do not want to change the display format permanently, and perhaps apply a new format later on, I personally favour the use of a resource manager (the with
statement in Python). In your case you could do something like this:
with pd.option_context('display.float_format', '${:0.2f}'.format):
print(df)
If you happen to need a different format further down in your code, you can change it by varying just the format in the snippet above.
Similar to another suggestion, except will not obliterate actual zero:
if (ltrim($str, '0') != '') {
$str = ltrim($str, '0');
} else {
$str = '0';
}
Or as was suggested (as of PHP 5.3), shorthand ternary operator can be used:
$str = ltrim($str, '0') ?: '0';
Here are the instructions from github:
touch README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/tqisjim/google-oauth.git
git push -u origin master
Here's what actually worked:
touch README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/tqisjim/google-oauth.git
git clone origin master
After cloning, then the push command succeeds by prompting for a username and password
I tried various different methods:
printexec() {
printf -- "\033[1;37m$\033[0m"
printf -- " %q" "$@"
printf -- "\n"
eval -- "$@"
eval -- "$*"
"$@"
"$*"
}
Output:
$ printexec echo -e "foo\n" bar
$ echo -e foo\\n bar
foon bar
foon bar
foo
bar
bash: echo -e foo\n bar: command not found
As you can see, only the third one, "$@"
gave the correct result.
Open Office / LibreOffice based solutions will do an OK job, but don't expect your PDFs to resemble your source files if they were created in MS-Office. A PDF that looks 90% like the original is not considered to be acceptable in many fields.
The only way to make sure your PDFs look exactly like the originals is to use a solution that uses the official MS-Office DLLs under the hood. If you are running your PHP solution on non-Windows based servers then it requires an additional Windows Server. This may be a showstopper, but if you really care about the look and feel of your PDFs you may not have an option.
Have a look at this blog post. It shows how to use PHP to convert MS-Office files with a high level of fidelity.
Disclaimer: I wrote this blog post and worked on a related commercial product, so consider me biased. However, it appears to be a great solution for the PHP people I work with.
Any of this answers didn't work for me so here is code which trust any certificates.
import java.io.IOException;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class HttpsClientBuilder {
public static DefaultHttpClient getBelieverHttpsClient() {
DefaultHttpClient client = null;
SchemeRegistry Current_Scheme = new SchemeRegistry();
Current_Scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
try {
Current_Scheme.register(new Scheme("https", new Naive_SSLSocketFactory(), 8443));
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpParams Current_Params = new BasicHttpParams();
int timeoutConnection = 8000;
HttpConnectionParams.setConnectionTimeout(Current_Params, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(Current_Params, timeoutSocket);
ThreadSafeClientConnManager Current_Manager = new ThreadSafeClientConnManager(Current_Params, Current_Scheme);
client = new DefaultHttpClient(Current_Manager, Current_Params);
//HttpPost httpPost = new HttpPost(url);
//client.execute(httpPost);
return client;
}
public static class Naive_SSLSocketFactory extends SSLSocketFactory
{
protected SSLContext Cur_SSL_Context = SSLContext.getInstance("TLS");
public Naive_SSLSocketFactory ()
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException
{
super(null, null, null, null, null, (X509HostnameVerifier)null);
Cur_SSL_Context.init(null, new TrustManager[] { new X509_Trust_Manager() }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException
{
return Cur_SSL_Context.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException
{
return Cur_SSL_Context.getSocketFactory().createSocket();
}
}
private static class X509_Trust_Manager implements X509TrustManager
{
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
};
}
I've been looking into this approach:
function getServerObject(serverObject) {
if (typeof serverObject === "undefined") {
return null;
}
return serverObject;
}
var itCameFromDotNet = getServerObject(@dotNetObject);
To me this seems to make it safer on the JS side... worst case you end up with a null variable.
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:
2nd Child:
td:first-child + td
3rd Child:
td:first-child + td + td
Then simply add another + td
for each additional child you wish to select.
If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):
$(function() {
$('td:first-child').addClass("firstChild");
$(".table-class tr").each(function() {
$(this).find('td:eq(1)').addClass("secondChild");
$(this).find('td:eq(2)').addClass("thirdChild");
});
});
Then in your css you simply use those class selectors to make whatever changes you like:
table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }
How you test depends on the Property's DataType:
| Type | Test | Test2 | Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then | | Boolen (True/False) | If Not obj.Property Then | If obj.Property = False Then | Object | If obj.Property Is Nothing Then | | String | If obj.Property = "" Then | If LenB(obj.Property) = 0 Then | Variant | If obj.Property = Empty Then |
You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)
The vector of raw (non-normalized) predictions that a classification model generates, which is ordinarily then passed to a normalization function. If the model is solving a multi-class classification problem, logits typically become an input to the softmax function. The softmax function then generates a vector of (normalized) probabilities with one value for each possible class.
In addition, logits sometimes refer to the element-wise inverse of the sigmoid function. For more information, see tf.nn.sigmoid_cross_entropy_with_logits.
Where can I download (certified) 64 bit Apache httpd binaries for Windows?
Right now, there are none. The Apache Software Foundation produces Open Source Software. The 32 bit binaries provided are a courtesy of the community members.
Though there are some unofficial e.g. http://www.apachelounge.com/download/win64/, but I have no idea if they can be trusted.
For the syntax, it looks like this (leave out the column list to implicitly mean "all")
INSERT INTO this_table_archive
SELECT *
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00'
For avoiding primary key errors if you already have data in the archive table
INSERT INTO this_table_archive
SELECT t.*
FROM this_table t
LEFT JOIN this_table_archive a on a.id=t.id
WHERE t.entry_date < '2011-01-01 00:00:00'
AND a.id is null # does not yet exist in archive
Warning: Unfortunately I believe most popular platforms have dropped support for comprehensions. See below for the well-supported ES6 method
You can always use something like:
[for (i of Array(7).keys()) i*i];
Running this code on Firefox:
[ 0, 1, 4, 9, 16, 25, 36 ]
This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.
This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:
var range = (u, l = 0) => [ for( i of Array(u - l).keys() ) i + l ]
Then you can do:
[for (i of range(5)) i*i] // 0, 1, 4, 9, 16, 25
[for (i of range(5,3)) i*i] // 9, 16, 25
A nice way to do this any of:
[...Array(7).keys()].map(i => i * i);
Array(7).fill().map((_,i) => i*i);
[...Array(7)].map((_,i) => i*i);
This will output:
[ 0, 1, 4, 9, 16, 25, 36 ]
ctrl + d
kills a window in linux terminal, also works in tmux.
This is kind of a approach.
No there isn't. You can only read information associated with the current domain.
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
You should iterate over the keys and get the values using square brackets.
See: How do I enumerate the properties of a javascript object?
EDIT: Obviously, this makes the question a duplicate.
HTTP Basic + HTTPS is one common method.