I think the only cookie you need is JSESSIONID=xxx..
Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
Results I had varied by browser.
Chrome- 127.0.0.1 worked but localhost .localhost and "" did not. Firefox- .localhost worked but localhost, 127.0.0.1, and "" did not.
Have not tested in Opera, IE, or Safari
In Linux, you can issue kill -TSTP <pid>
to the background and stop a process. So, it's there, but not consuming CPU time.
Then later, kill -CONT <pid>
and it's off and running again.
The short answer is "yes". A sample ldapsearch
command to query an Active Directory server is:
ldapsearch \
-x -h ldapserver.mydomain.com \
-D "[email protected]" \
-W \
-b "cn=users,dc=mydomain,dc=com" \
-s sub "(cn=*)" cn mail sn
This would connect to an AD server at hostname ldapserver.mydomain.com
as user [email protected]
, prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com
subtree.
See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.
The <colgroup>
and <col>
tags that lives inside tables are designed for this purpose. If you have three columns in your table and want to align the third, add this after your opening <table>
tag:
<colgroup>
<col />
<col />
<col class="your-right-align-class" />
</colgroup>
along with the requisite CSS:
.your-right-align-class { text-align: right; }
From the W3:
Definition and Usage
The
<col>
tag defines attribute values for one or more columns in a table.The
<col>
tag is useful for applying styles to entire columns, instead of repeating the styles for each cell, for each row.
The solution for me was to include
<configuration>
<config>
<add key="http_proxy" value="http://<IP>:<Port>" />
<add key="http_proxy.user" value="<user>" />
<add key="http_proxy.password" value="<password>" />
</config>
</configuration>
In the nuget.config
file.
A possible solution:
<?php
$txt = "data.txt";
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
You were closing the script before close de file.
If you want to temporarily get rid of these console errors (like I did) you can install the extension here: https://chrome.google.com/webstore/detail/google-cast/boadgeojelhgndaghljhdicfkmllpafd/reviews?hl=en
I left a review asking for a fix. You can also do a bug report via the extension (after you install it) here. Instructions for doing so are here: https://support.google.com/chromecast/answer/3187017?hl=en
I hope Google gets on this. I need my console to show my errors, etc. Not theirs.
If you have properly structured your tables so that each contains relatively unique values, then the less intensive way to do this would be to do 3 separate insert-into statements, 1 for each table, with the join-filter in place for each insert -
INSERT INTO SkusBought...
SELECT t1.customer, t1.SKU, t1.TypeDesc
FROM transactiondatatransit AS T1
LEFT OUTER JOIN topThreetransit AS T2
ON t1.customer = t2.customernum
WHERE T2.customernum IS NOT NULL
Repeat this for the other two tables - copy/paste is a fine method, simply change the FROM table name. ** IF you are trying to prevent duplicated entries in your SkusBought table you can add the following join code in each section prior to the WHERE clause.
LEFT OUTER JOIN SkusBought AS T3
ON t1.customer = t3.customer
AND t1.sku = t3.sku
-and then the last line of WHERE clause-
AND t3.customer IS NULL
Your initial code is using a number of sub-queries, and the UNION statement can be expensive as it will first create its own temporary table to populate the data from the three separate sources before inserting into the table you want ALONG with running another sub-query to filter results.
CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@Id INT
AS
BEGIN
-- SP Logic
END
Procedure Calling
DECLARE @return_value nvarchar(50)
EXEC @return_value = GetTaskEvents
@TaskName = 'TaskName',
@Id =2
SELECT 'Return Value' = @return_value
Ah... the rationale for not having a straightforward method in Java to do that is file storage abstraction: some filesystems may not have the number of files in a directory readily available... that count may not even have any meaning at all (see for example distributed, P2P filesystems, fs that store file lists as a linked list, or database-backed filesystems...). So yes,
new File(<directory path>).list().length
is probably your best bet.
I found a (much) better code to do this if you want to check for anything in $@
.
if [[ $1 = "" ]] then echo '$1 is blank' else echo '$1 is filled up' fi
Why this all? Everything in $@
exists in Bash, but by default it's blank, so test -z
and test -n
couldn't help you.
Update: You can also count number of characters in a parameters.
if [ ${#1} = 0 ] then echo '$1 is blank' else echo '$1 is filled up' fi
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
If the response code isn't 200 or 2xx, use getErrorStream()
instead of getInputStream().
The above error run the commend line\
please change the command $ node server it's working and server is started
There are plenty of built in python modules that whould help with this. For example urllib and htmllib.
The problem will be simpler if you change the way you're approaching it. You say you want to "fill some forms, click submit button, send the data back to server, recieve the response", which sounds like a four stage process.
In fact, what you need to do is post some data to a webserver and get a response.
This is as simple as:
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()
(example taken from the urllib docs).
What you do with the response depends on how complex the HTML is and what you want to do with it. You might get away with parsing it using a regular expression or two, or you can use the htmllib.HTMLParser class, or maybe a higher level more flexible parser like Beautiful Soup.
It exists a property called XmlElementAttribute.IsNullable
If the IsNullable property is set to true, the xsi:nil attribute is generated for class members that have been set to a null reference.
The following example shows a field with the XmlElementAttribute
applied to it, and the IsNullable property set to false.
public class MyClass
{
[XmlElement(IsNullable = false)]
public string Group;
}
You can have a look to other XmlElementAttribute
for changing names in serialization etc.
Just had this issue but had to find the config for IIS Express so I could add the mime types. For me, it was located at C:\Users\<username>\Documents\IISExpress\config\applicationhost.config
and I was able to add in the correct "mime map" there.
Here is an example I think that will help you
<!DOCTYPE html>
<html>
<head>
<script src="js/min.js"></script>
<script src="js/pdf.js"></script>
<script>
$(function(){
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
var table = tableToJson($('#StudentInfoListTable').get(0))
var doc = new jsPDF('p','pt', 'a4', true);
doc.cellInitialize();
$.each(table, function (i, row){
console.debug(row);
$.each(row, function (j, cell){
doc.cell(10, 50,120, 50, cell, i); // 2nd parameter=top margin,1st=left margin 3rd=row cell width 4th=Row height
})
})
doc.save('sample-file.pdf');
});
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
// go through cells
for (var i=0; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
});
</script>
</head>
<body>
<div id="table">
<table id="StudentInfoListTable">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Track</th>
<th>S.S.C Roll</th>
<th>S.S.C Division</th>
<th>H.S.C Roll</th>
<th>H.S.C Division</th>
<th>District</th>
</tr>
</thead>
<tbody>
<tr>
<td>alimon </td>
<td>Email</td>
<td>1</td>
<td>2222</td>
<td>as</td>
<td>3333</td>
<td>dd</td>
<td>33</td>
</tr>
</tbody>
</table>
<button id="cmd">Submit</button>
</body>
</html>
Here the output
I know this is old but just wanted to mention that I tried this with PHP 7.2:
<?php
//Creating array with 1 000 000 elements
$a = array();
for ($i = 0; $i < 1000000; ++$i)
{
$a[] = 100;
}
//Measure
$time = time();
for ($i = 0; $i < 1000000000; ++$i)
{
$b = count($a);
}
print("1 000 000 000 iteration of count() took ".(time()-$time)." sec\n");
$time = time();
for ($i = 0; $i < 1000000000; ++$i)
{
$b = sizeof($a);
}
print("1 000 000 000 iteration of sizeof() took ".(time()-$time)." sec\n");
?>
and the result was:
1 000 000 000 iteration of count() took 414 sec
1 000 000 000 iteration of sizeof() took 1369 sec
So just use count()
.
You need to get the HLS m3u8 playlist files from the video's manifest. There are ways to do this by hand, but for simplicity I'll be using the youtube-dl tool to get this information. I'll be using this live stream as an example: https://www.youtube.com/watch?v=_Gtc-GtLlTk
First, get the formats of the video:
? ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] Downloading multifeed video (_Gtc-GtLlTk, aflWCT1tYL0) - add --no-playlist to just download video _Gtc-GtLlTk
[download] Downloading playlist: Southwest Florida Eagle Cam
[youtube] playlist Southwest Florida Eagle Cam: Collected 2 video ids (downloading 2 of them)
[download] Downloading video 1 of 2
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] _Gtc-GtLlTk: Extracting video information
[youtube] _Gtc-GtLlTk: Downloading formats manifest
[youtube] _Gtc-GtLlTk: Downloading DASH manifest
[info] Available formats for _Gtc-GtLlTk:
format code extension resolution note
140 m4a audio only DASH audio 144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160 mp4 256x144 DASH video 124k , avc1.42c00b, 30fps, video only
133 mp4 426x240 DASH video 258k , avc1.4d4015, 30fps, video only
134 mp4 640x360 DASH video 646k , avc1.4d401e, 30fps, video only
135 mp4 854x480 DASH video 1171k , avc1.4d401f, 30fps, video only
136 mp4 1280x720 DASH video 2326k , avc1.4d401f, 30fps, video only
137 mp4 1920x1080 DASH video 4347k , avc1.640028, 30fps, video only
151 mp4 72p HLS , h264, aac @ 24k
132 mp4 240p HLS , h264, aac @ 48k
92 mp4 240p HLS , h264, aac @ 48k
93 mp4 360p HLS , h264, aac @128k
94 mp4 480p HLS , h264, aac @128k
95 mp4 720p HLS , h264, aac @256k
96 mp4 1080p HLS , h264, aac @256k (best)
[download] Downloading video 2 of 2
[youtube] aflWCT1tYL0: Downloading webpage
[youtube] aflWCT1tYL0: Downloading video info webpage
[youtube] aflWCT1tYL0: Extracting video information
[youtube] aflWCT1tYL0: Downloading formats manifest
[youtube] aflWCT1tYL0: Downloading DASH manifest
[info] Available formats for aflWCT1tYL0:
format code extension resolution note
140 m4a audio only DASH audio 144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160 mp4 256x144 DASH video 124k , avc1.42c00b, 30fps, video only
133 mp4 426x240 DASH video 258k , avc1.4d4015, 30fps, video only
134 mp4 640x360 DASH video 646k , avc1.4d401e, 30fps, video only
135 mp4 854x480 DASH video 1171k , avc1.4d401f, 30fps, video only
136 mp4 1280x720 DASH video 2326k , avc1.4d401f, 30fps, video only
151 mp4 72p HLS , h264, aac @ 24k
132 mp4 240p HLS , h264, aac @ 48k
92 mp4 240p HLS , h264, aac @ 48k
93 mp4 360p HLS , h264, aac @128k
94 mp4 480p HLS , h264, aac @128k
95 mp4 720p HLS , h264, aac @256k (best)
[download] Finished downloading playlist: Southwest Florida Eagle Cam
In this case, there are two videos because the live stream contains two cameras. From here, we need to get the HLS URL for a specific stream. Use -f
to pass in the format you would like to watch, and -g
to get that stream's URL:
? ~ youtube-dl -f 95 -g https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/_Gtc-GtLlTk.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/X0d0Yy1HdExsVGsuMg.95/hls_chunk_host/r1---sn-ab5l6ne6.googlevideo.com/playlist_type/LIVE/gcr/us/pmbypass/yes/mm/32/mn/sn-ab5l6ne6/ms/lv/mv/m/pl/20/dover/3/sver/3/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/upn/xmL7zNht848/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434315/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,playlist_type,gcr,pmbypass,mm,mn,ms,mv,pl/signature/7E48A727654105FF82E158154FCBA7569D52521B.1FA117183C664F00B7508DDB81274644F520C27F/key/dg_yt0/playlist/index.m3u8
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/aflWCT1tYL0.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/YWZsV0NUMXRZTDAuMg.95/hls_chunk_host/r13---sn-ab5l6n7y.googlevideo.com/pmbypass/yes/playlist_type/LIVE/gcr/us/mm/32/mn/sn-ab5l6n7y/ms/lv/mv/m/pl/20/dover/3/sver/3/upn/vdBkD9lrq8Q/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434316/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,pmbypass,playlist_type,gcr,mm,mn,ms,mv,pl/signature/4E83CD2DB23C2331CE349CE9AFE806C8293A01ED.880FD2E253FAC8FA56FAA304C78BD1D62F9D22B4/key/dg_yt0/playlist/index.m3u8
These are your HLS m3u8 playlists, one for each camera associated with the live stream.
Without youtube-dl, your flow might look like this:
Take your video id and make a GET request to the get_video_info
endpoint:
HTTP GET: https://www.youtube.com/get_video_info?&video_id=_Gtc-GtLlTk&el=info&ps=default&eurl=&gl=US&hl=en
In the response, the hlsvp
value will be the link to the m3u8 HLS playlist:
https://manifest.googlevideo.com/api/manifest/hls_variant/maudio/1/ipbits/0/key/yt6/ip/64.125.177.124/gcr/us/source/yt_live_broadcast/upn/BYS1YGuQtYI/id/_Gtc-GtLlTk.2/fexp/9416126%2C9416984%2C9417367%2C9420452%2C9422596%2C9423039%2C9423661%2C9423662%2C9423923%2C9425346%2C9427672%2C9428946%2C9429162/sparams/gcr%2Cid%2Cip%2Cipbits%2Citag%2Cmaudio%2Cplaylist_type%2Cpmbypass%2Csource%2Cexpire/sver/3/expire/1456449859/pmbypass/yes/playlist_type/LIVE/itag/0/signature/1E6874232CCAC397B601051699A03DC5A32F66D9.1CABCD9BFC87A2A886A29B86CF877077DD1AEEAA/file/index.m3u8
Have you seen this one? From http://www.aspspider.com/resources/Resource510.aspx:
public DataTable Import(String path)
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.ActiveSheet;
int index = 0;
object rowIndex = 2;
DataTable dt = new DataTable();
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("Mobile");
dt.Columns.Add("Landline");
dt.Columns.Add("Email");
dt.Columns.Add("ID");
DataRow row;
while (((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2 != null)
{
row = dt.NewRow();
row[0] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2);
row[1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 2]).Value2);
row[2] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 3]).Value2);
row[3] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 4]).Value2);
row[4] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 5]).Value2);
index++;
rowIndex = 2 + index;
dt.Rows.Add(row);
}
app.Workbooks.Close();
return dt;
}
I'm new to git but it seems that if I do git checkout for each directory then it works. Also, the sparse-checkout file needs to have a trailing slash after every directory as indicated. Someone more experience please confirm that this will work.
Interestingly, if you checkout a directory not in the sparse-checkout file it seems to make no difference. They don't show up in git status and git read-tree -m -u HEAD doesn't cause it to be removed. git reset --hard doesn't cause the directory to be removed either. Anyone more experienced care to comment on what git thinks of directories that are checked out but which are not in the sparse checkout file?
Use the wait
built-in:
process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait
For the above example, 4 processes process1
... process4
would be started in the background, and the shell would wait until those are completed before starting the next set.
From the GNU manual:
wait [jobspec or pid ...]
Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.
The way I'd solve the problem is just
$a$b
For example,
a="Hello"
b=" World"
c=$a$b
echo "$c"
which produces
Hello World
If you try to concatenate a string with another string, for example,
a="Hello"
c="$a World"
then echo "$c"
will produce
Hello World
with an extra space.
$aWorld
doesn't work, as you may imagine, but
${a}World
produces
HelloWorld
Native Groovy GET and POST
// GET
def get = new URL("https://httpbin.org/get").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if(getRC.equals(200)) {
println(get.getInputStream().getText());
}
// POST
def post = new URL("https://httpbin.org/post").openConnection();
def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(200)) {
println(post.getInputStream().getText());
}
You code is ok only except that you can't add same class test1
.
$('.page-address-edit').addClass('test1').addClass('test2'); //this will add test1 and test2
And you could also do
$('.page-address-edit').addClass('test1 test2');
The simplest solution to run two Python processes concurrently is to run them from a bash file, and tell each process to go into the background with the &
shell operator.
python script1.py &
python script2.py &
For a more controlled way to run many processes in parallel, look into the Supervisor project, or use the multiprocessing module to orchestrate from inside Python.
Grant required permission ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION after start service
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import java.util.concurrent.TimeUnit;
/**
* Created by Ketan Ramani on 05/11/18.
*/
public class BackgroundLocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
/* Declare in manifest
<service android:name=".BackgroundLocationUpdateService"/>
*/
private final String TAG = "BackgroundLocationUpdateService";
private final String TAG_LOCATION = "TAG_LOCATION";
private Context context;
private boolean stopService = false;
/* For Google Fused API */
protected GoogleApiClient mGoogleApiClient;
protected LocationSettingsRequest mLocationSettingsRequest;
private String latitude = "0.0", longitude = "0.0";
private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationCallback mLocationCallback;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
/* For Google Fused API */
@Override
public void onCreate() {
super.onCreate();
context = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
StartForeground();
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
try {
if (!stopService) {
//Perform your task here
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (!stopService) {
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(10));
}
}
}
};
handler.postDelayed(runnable, 2000);
buildGoogleApiClient();
return START_STICKY;
}
@Override
public void onDestroy() {
Log.e(TAG, "Service Stopped");
stopService = true;
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
Log.e(TAG_LOCATION, "Location Update Callback Removed");
}
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void StartForeground() {
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
String CHANNEL_ID = "channel_location";
String CHANNEL_NAME = "channel_location";
NotificationCompat.Builder builder = null;
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
builder.setChannelId(CHANNEL_ID);
builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
} else {
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
}
builder.setContentTitle("Your title");
builder.setContentText("You are now online");
Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(notificationSound);
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_logo);
builder.setContentIntent(pendingIntent);
Notification notification = builder.build();
startForeground(101, notification);
}
@Override
public void onLocationChanged(Location location) {
Log.e(TAG_LOCATION, "Location Changed Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
if (latitude.equalsIgnoreCase("0.0") && longitude.equalsIgnoreCase("0.0")) {
requestLocationUpdate();
} else {
Log.e(TAG_LOCATION, "Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mLocationSettingsRequest = builder.build();
mSettingsClient
.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.e(TAG_LOCATION, "GPS Success");
requestLocationUpdate();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
int REQUEST_CHECK_SETTINGS = 214;
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult((AppCompatActivity) context, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
Log.e(TAG_LOCATION, "Unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.e(TAG_LOCATION, "Location settings are inadequate, and cannot be fixed here. Fix in Settings.");
}
}
}).addOnCanceledListener(new OnCanceledListener() {
@Override
public void onCanceled() {
Log.e(TAG_LOCATION, "checkLocationSettings -> onCanceled");
}
});
}
@Override
public void onConnectionSuspended(int i) {
connectGoogleClient();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
mSettingsClient = LocationServices.getSettingsClient(context);
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
connectGoogleClient();
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Log.e(TAG_LOCATION, "Location Received");
mCurrentLocation = locationResult.getLastLocation();
onLocationChanged(mCurrentLocation);
}
};
}
private void connectGoogleClient() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int resultCode = googleAPI.isGooglePlayServicesAvailable(context);
if (resultCode == ConnectionResult.SUCCESS) {
mGoogleApiClient.connect();
}
}
@SuppressLint("MissingPermission")
private void requestLocationUpdate() {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
}
In Activity
Start Service : startService(new Intent(this, BackgroundLocationUpdateService.class));
Stop Service : stopService(new Intent(this, BackgroundLocationUpdateService.class));
In Fragment
Start Service : getActivity().startService(new Intent(getActivity().getBaseContext(), BackgroundLocationUpdateService.class));
Stop Service : getActivity().stopService(new Intent(getActivity(), BackgroundLocationUpdateService.class));
add these in app level dependencies
implementation 'com.android.support:asynclayoutinflater:28.0.0'
implementation 'com.android.support:exifinterface:28.0.0'
implementation 'com.android.support:animated-vector-drawable:28.0.0'
implementation 'com.android.support:support-media-compat:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
I think you're getting confused about what can hold what in JSON.Net.
JToken
is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.JProperty
is a single JToken
value paired with a name. It can only be added to a JObject
, and its value cannot be another JProperty
.JObject
is a collection of JProperties
. It cannot hold any other kind of JToken
directly.In your code, you are attempting to add a JObject
(the one containing the "banana" data) to a JProperty
("orange") which already has a value (a JObject
containing {"colour":"orange","size":"large"}
). As you saw, this will result in an error.
What you really want to do is add a JProperty
called "banana" to the JObject
which contains the other fruit JProperties
. Here is the revised code:
JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));
If you use cv2
, correct method is to use .copy()
method in Numpy. It will create a copy of the array you need. Otherwise it will produce only a view of that object.
eg:
In [1]: import numpy as np
In [2]: x = np.arange(10*10).reshape((10,10))
In [4]: y = x[3:7,3:7].copy()
In [6]: y[2,2] = 1000
In [8]: 1000 in x
Out[8]: False # see, 1000 in y doesn't change values in x, parent array.
Sometimes, it may help switching off AllowAutoRedirect
and setting both login POST
and page GET
requests the same user agent.
request.UserAgent = userAgent;
request.AllowAutoRedirect = false;
If you are implementing your bot, keep stored a group name -> id table, and ask it with a command. Then you can also send per name.
Apart from HTML 5 data-tip You can use css also for making a totally customizable tooltip to be used anywhere throughout your markup.
/* ToolTip classses */ _x000D_
.tooltip {_x000D_
display: inline-block; _x000D_
}_x000D_
.tooltip .tooltiptext {_x000D_
margin-left:9px;_x000D_
width : 320px;_x000D_
visibility: hidden;_x000D_
background-color: #FFF;_x000D_
border-radius:4px;_x000D_
border: 1px solid #aeaeae;_x000D_
position: absolute;_x000D_
z-index: 1;_x000D_
padding: 5px;_x000D_
margin-top : -15px; _x000D_
opacity: 0;_x000D_
transition: opacity 0.5s;_x000D_
}_x000D_
.tooltip .tooltiptext::after {_x000D_
content: " ";_x000D_
position: absolute;_x000D_
top: 5%;_x000D_
right: 100%; _x000D_
margin-top: -5px;_x000D_
border-width: 5px;_x000D_
border-style: solid;_x000D_
border-color: transparent #aeaeae transparent transparent;_x000D_
}_x000D_
_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
<input type="text" />_x000D_
<span class="tooltiptext">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </span>_x000D_
</div>
_x000D_
One possible solution is to encode the data in your app and use decoding at runtime (when you want to use that data). I also recommend to use progaurd to make it hard to read and understand the decompiled source code of your app . for example I put a encoded key in the app and then used a decode method in my app to decode my secret keys at runtime:
// "the real string is: "mypassword" ";
//encoded 2 times with an algorithm or you can encode with other algorithms too
public String getClientSecret() {
return Utils.decode(Utils
.decode("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}
Decompiled source code of a proguarded app is this:
public String c()
{
return com.myrpoject.mypackage.g.h.a(com.myrpoject.mypackage.g.h.a("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}
At least it's complicated enough for me. this is the way I do when I have no choice but store a value in my application. Of course we all know It's not the best way but it works for me.
/**
* @param input
* @return decoded string
*/
public static String decode(String input) {
// Receiving side
String text = "";
try {
byte[] data = Decoder.decode(input);
text = new String(data, "UTF-8");
return text;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "Error";
}
Decompiled version:
public static String a(String paramString)
{
try
{
str = new String(a.a(paramString), "UTF-8");
return str;
}
catch (UnsupportedEncodingException localUnsupportedEncodingException)
{
while (true)
{
localUnsupportedEncodingException.printStackTrace();
String str = "Error";
}
}
}
and you can find so many encryptor classes with a little search in google.
Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:
EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")
After that you can do this:
EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )
R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.
Both the databases and tables should have character set utf8mb4
and collation utf8mb4_unicode_ci
.
When creating a new database you should use:
CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
If you have an existing database and you want to add support:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
You also need to set the correct character set and collation for your tables:
CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
or change it if you've got existing tables with a lot of data:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Note that utf8_general_ci
is no longer recommended best practice. See the related Q & A:
What's the difference between utf8_general_ci and utf8_unicode_ci on Stack Overflow.
You can also use npmlog by issacs, recommended in https://npmjs.org/doc/coding-style.html.
You can find this module here https://github.com/isaacs/npmlog
Let's fill in the gaps in your code, by adding the other branches in the logic, and see what happens:
SQL> DECLARE
2 str1 varchar2(4000);
3 str2 varchar2(4000);
4 BEGIN
5 str1:='';
6 str2:='sdd';
7 IF(str1<>str2) THEN
8 dbms_output.put_line('The two strings is not equal');
9 ELSIF (str1=str2) THEN
10 dbms_output.put_line('The two strings are the same');
11 ELSE
12 dbms_output.put_line('Who knows?');
13 END IF;
14 END;
15 /
Who knows?
PL/SQL procedure successfully completed.
SQL>
So the two strings are neither the same nor are they not the same? Huh?
It comes down to this. Oracle treats an empty string as a NULL. If we attempt to compare a NULL and another string the outcome is not TRUE nor FALSE, it is NULL. This remains the case even if the other string is also a NULL.
new BigInteger(1, myString.getBytes(/*YOUR_CHARSET?*/)).toString(16)
Try this code. Call it before making any http requests. The code will use the proxy from your Internet Explorer Settings - one thing though, I use proxy.Credentials = ....
because my proxy server is an NTLM authenticated Internet Acceleration Server. Give it a whizz.
static void setProxy()
{
WebProxy proxy = (WebProxy)WebProxy.GetDefaultProxy();
if(proxy.Address != null)
{
proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
WebRequest.DefaultWebProxy = new System.Net.WebProxy(proxy.Address, proxy.BypassProxyOnLocal, proxy.BypassList, proxy.Credentials);
}
}
This will add an image to another.
using (Graphics grfx = Graphics.FromImage(image))
{
grfx.DrawImage(newImage, x, y)
}
Graphics is in the namespace System.Drawing
If you need a laymans explanation of the use beyond that provided in the Spring Docs
Consider this code...
class Service {
@Transactional(propagation=Propagation.REQUIRED)
public void doSomething() {
// access a database using a DAO
}
}
When doSomething() is called it knows it has to start a Transaction on the database before executing. If the caller of this method has already started a Transaction then this method will use that same physical Transaction on the current database connection.
This @Transactional
annotation provides a means of telling your code when it executes that it must have a Transaction. It will not run without one, so you can make this assumption in your code that you wont be left with incomplete data in your database, or have to clean something up if an exception occurs.
Transaction management is a fairly complicated subject so hopefully this simplified answer is helpful
A Popen
object has a .wait()
method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).
If you use this method, you'll prevent that the process zombies are lying around for too long.
(Alternatively, you can use subprocess.call()
or subprocess.check_call()
for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_
)call()
.)
If you have several subprocesses to wait for, you can do
exit_codes = [p.wait() for p in p1, p2]
which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.
If you use
std::vector<std::reference_wrapper<std::string>> names{ };
Do not forget, when you use auto in the for loop, to use also get, like this:
for (auto element in : names)
{
element.get()//do something
}
Make sure you have qmake in your path (which qmake), and that it works (qmake -v) (IF you have to kill it with ctr-c then there is something wrong with your environment).
Then follow this: http://developer.qt.nokia.com/doc/qt-4.8/gettingstartedqt.html
Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation
function orientationhandler(evt){
// For FF3.6+
if (!evt.gamma && !evt.beta) {
evt.gamma = -(evt.x * (180 / Math.PI));
evt.beta = -(evt.y * (180 / Math.PI));
}
// use evt.gamma, evt.beta, and evt.alpha
// according to dev.w3.org/geo/api/spec-source-orientation
}
window.addEventListener('deviceorientation', orientationhandler, false);
window.addEventListener('MozOrientation', orientationhandler, false);
Use not
, for example:
return not myval
You cannot treat ==
or ||
as chars, since they are not chars, but a sequence of chars.
You could make your switch...case work on strings instead.
As answered misc.imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. imageio is one option,it will return object of type :
<class 'imageio.core.util.Image'>
but instead of imageio, use cv2
import cv2
im = cv2.imread('astronaut.png')
im will be of type :
<class 'numpy.ndarray'>
As numpy arrays are faster to compute.
Its is possible by using mach_inject. Take a look at Death to .DS_Store
I found that overriding HFSPlusPropertyStore::FlushChanges() with a function that simply did nothing, successfully prevented the creation of .DS_Store files on both Snow Leopard and Lion.
NOTE: On 10.11 you can not inject code into system apps.
a = [0,1,2,3]
a.drop(1)
# => [1, 2, 3]
a
# => [0,1,2,3]
and additionally:
[0,1,2,3].drop(2)
=> [2, 3]
[0,1,2,3].drop(3)
=> [3]
Not directly answering your question but something to remember:
When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.
from: http://us2.php.net/manual/en/function.include.php#84052
Might be a pasting problem, but as far as I can see from your code, you're missing the single quotes around the HTML part you're echo-ing.
If not, could you post the code correctly and tell us what line is causing the error?
String hashWith256(String textToHash) {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] byteOfTextToHash = textToHash.getBytes(StandardCharsets.UTF_8);
byte[] hashedByetArray = digest.digest(byteOfTextToHash);
String encoded = Base64.getEncoder().encodeToString(hashedByetArray);
return encoded;
}
There is no format specifier for bool
types. However, since any integral type shorter than int
is promoted to int
when passed down to printf()
's variadic arguments, you can use %d
:
bool x = true;
printf("%d\n", x); // prints 1
But why not:
printf(x ? "true" : "false");
or, better:
printf("%s", x ? "true" : "false");
or, even better:
fputs(x ? "true" : "false", stdout);
instead?
You can use any on process for dynamic path on command prompt
Process p = Runtime.getRuntime().exec("cmd.exe /c start dir ");
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"E:\\rakhee\\Obligation Extractions\" && dir");
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"E:\\oxyzen-workspace\\BrightleafDesktop\\Obligation Extractions\" && dir");
What is a DLL?
DLL files are binary files that can contain executable code and resources like images, etc. Unlike applications, these cannot be directly executed, but an application will load them as and when they are required (or all at once during startup).
Are they important?
Most applications will load the DLL files they require at startup. If any of these are not found the system will not be able to start the process at all.
DLL files might require other DLL files
In the same way that an application requires a DLL file, a DLL file might be dependent on other DLL files itself. If one of these DLL files in the chain of dependency is not found, the application will not load. This is debugged easily using any dependency walker tools, like Dependency Walker.
There are so many of them in the system folders
Most of the system functionality is exposed to a user program in the form of DLL files as they are a standard form of sharing code / resources. Each functionality is kept separately in different DLL files so that only the required DLL files will be loaded and thus reduce the memory constraints on the system.
Installed applications also use DLL files
DLL files also becomes a form of separating functionalities physically as explained above. Good applications also try to not load the DLL files until they are absolutely required, which reduces the memory requirements. This too causes applications to ship with a lot of DLL files.
DLL Hell
However, at times system upgrades often breaks other programs when there is a version mismatch between the shared DLL files and the program that requires them. System checkpoints and DLL cache, etc. have been the initiatives from M$ to solve this problem. The .NET platform might not face this issue at all.
How do we know what's inside a DLL file?
You have to use an external tool like DUMPBIN or Dependency Walker which will not only show what publicly visible functions (known as exports) are contained inside the DLL files and also what other DLL files it requires and which exports from those DLL files this DLL file is dependent upon.
How do we create / use them?
Refer the programming documentation from your vendor. For C++, refer to LoadLibrary in MSDN.
var wrapper = $(document.body);
strings = [
"19 51 2.108997",
"20 47 2.1089"
];
$.each(strings, function(key, value) {
var tmp = value.split(" ");
$.each([
tmp[0] + " " + tmp[1],
tmp[2]
], function(key, value) {
$("<span>" + value + "</span>").appendTo(wrapper);
});
});
Generally speaking:
all
and any
are functions that take some iterable and return True
, if
all()
, no values in the iterable are falsy;any()
, at least one value is truthy.A value x
is falsy iff bool(x) == False
.
A value x
is truthy iff bool(x) == True
.
Any non-booleans in the iterable will be fine — bool(x)
will coerce any x
according to these rules: 0
, 0.0
, None
, []
, ()
, []
, set()
, and other empty collections will yield False
, anything else True
. The docstring for bool
uses the terms 'true'/'false' for 'truthy'/'falsy', and True
/False
for the concrete boolean values.
In your specific code samples:
You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:
if any(foobars) == big_foobar:
...because any(foobars)
would first be evaluated to either True
or False
, and then that boolean value would be compared to big_foobar
, which generally always gives you False
(unless big_foobar
coincidentally happened to be the same boolean value).
Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.
What you want instead is:
if any(x == big_foobar for x in foobars):
which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars
, it compares the item to big_foobar
and emits the resulting boolean into the resulting sequence:
tmp = (x == big_foobar for x in foobars)
then any
walks over all items in tmp
and returns True
as soon as it finds the first truthy element. It's as if you did the following:
In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']
In [2]: big_foobar = 'big'
In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True
Note: As DSM pointed out, any(x == y for x in xs)
is equivalent to y in xs
but the latter is more readable, quicker to write and runs faster.
Some examples:
In [1]: any(x > 5 for x in range(4))
Out[1]: False
In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True
In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True
In [4]: all([True, True, True, False, True])
Out[4]: False
See also: http://docs.python.org/2/library/functions.html#all
In reply to Dimitrys answer but using Ajax.BeginForm
the following works at least with MVC >5 (4 not tested).
write a model as shown in the other answers,
In the "parent view" you will probably use a table to show the data.
Model should be an ienumerable. I assume, the model has an id
-property. Howeverm below the template, a placeholder for the modal and corresponding javascript
<table>
@foreach (var item in Model)
{
<tr> <td id="[email protected]">
@Html.Partial("dataRowView", item)
</td> </tr>
}
</table>
<div class="modal fade" id="editor-container" tabindex="-1"
role="dialog" aria-labelledby="editor-title">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content" id="editor-content-container"></div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('.editor-container').click(function () {
var url = "/area/controller/MyEditAction";
var id = $(this).attr('data-id');
$.get(url + '/' + id, function (data) {
$('#editor-content-container').html(data);
$('#editor-container').modal('show');
});
});
});
function success(data,status,xhr) {
$('#editor-container').modal('hide');
$('#editor-content-container').html("");
}
function failure(xhr,status,error) {
$('#editor-content-container').html(xhr.responseText);
$('#editor-container').modal('show');
}
</script>
note the "editor-success-id" in data table rows.
The dataRowView
is a partial containing the presentation of an model's item.
@model ModelView
@{
var item = Model;
}
<div class="row">
// some data
<button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
</div>
Write the partial view that is called by clicking on row's button (via JS $('.editor-container').click(function () ...
).
@model Model
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="editor-title">Title</h4>
</div>
@using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "editor-success-" + @Model.Id,
OnSuccess = "success",
OnFailure = "failure",
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
<div class="modal-body">
<div class="form-horizontal">
// Models input fields
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
}
This is where magic happens: in AjaxOptions
, UpdateTargetId will replace the data row after editing, onfailure and onsuccess will control the modal.
This is, the modal will only close when editing was successful and there have been no errors, otherwise the modal will be displayed after the ajax-posting to display error messages, e.g. the validation summary.
But how to get ajaxform to know if there is an error? This is the controller part, just change response.statuscode as below in step 5:
the corresponding controller action method for the partial edit modal
[HttpGet]
public async Task<ActionResult> EditPartData(Guid? id)
{
// Find the data row and return the edit form
Model input = await db.Models.FindAsync(id);
return PartialView("EditModel", input);
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> MyEditAction([Bind(Include =
"Id,Fields,...")] ModelView input)
{
if (TryValidateModel(input))
{
// save changes, return new data row
// status code is something in 200-range
db.Entry(input).State = EntityState.Modified;
await db.SaveChangesAsync();
return PartialView("dataRowView", (ModelView)input);
}
// set the "error status code" that will redisplay the modal
Response.StatusCode = 400;
// and return the edit form, that will be displayed as a
// modal again - including the modelstate errors!
return PartialView("EditModel", (Model)input);
}
This way, if an error occurs while editing Model data in a modal window, the error will be displayed in the modal with validationsummary methods of MVC; but if changes were committed successfully, the modified data table will be displayed and the modal window disappears.
Note: you get ajaxoptions working, you need to tell your bundles configuration to bind jquery.unobtrusive-ajax.js
(may be installed by NuGet):
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax.js"));
'Greedy' means match longest possible string.
'Lazy' means match shortest possible string.
For example, the greedy h.+l
matches 'hell'
in 'hello'
but the lazy h.+?l
matches 'hel'
.
PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus
a (.) period
is used for string concatenation.
<?php
$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
$selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;
?>
might be late also like the other answer but I did this early this year and the solution I came up with is using css.
$(window).bind('resize', function () {
/*the line below was causing the page to keep loading.
$('#tableData').dataTable().fnAdjustColumnSizing();
Below is a workaround. The above should automatically work.*/
$('#tableData').css('width', '100%');
} );
Visual Studio reads NuGet.Config files from the solution root. Try moving it there instead of placing it in the same folder as the project.
You can also place the file at %appdata%\NuGet\NuGet.Config
and it will be used everywhere.
https://docs.microsoft.com/en-us/nuget/schema/nuget-config-file
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
The problem here involves type casting.
When you add int and long,
But +=
is coded in such a way that it does type casting. i=(int)(i+m)
I keep coming back to these questions trying to figure out where exactly the data I'm interested in is buried in what is truly a monolithic ErrorRecord structure. Almost all answers give piecemeal instructions on how to pull certain bits of data.
But I've found it immensely helpful to dump the entire object with ConvertTo-Json
so that I can visually see LITERALLY EVERYTHING in a comprehensible layout.
try {
Invoke-WebRequest...
}
catch {
Write-Host ($_ | ConvertTo-Json)
}
Use ConvertTo-Json
's -Depth
parameter to expand deeper values, but use extreme caution going past the default depth of 2
:P
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json
Issue has been resolved after updating Android studio version to 3.3-rc2 or latest released version.
cr: @shadowsheep
have to change version under /gradle/wrapper/gradle-wrapper.properties. refer below url https://stackoverflow.com/a/56412795/7532946
When you have Overridden Methods with same Name Use the helper below
public static TValue GetControllerMethodAttributeValue<T, TT, TAttribute, TValue>(this T type, Expression<Func<T, TT>> exp, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute
{
var memberExpression = exp?.Body as MethodCallExpression;
if (memberExpression.Method.GetCustomAttributes(typeof(TAttribute), false).FirstOrDefault() is TAttribute attr && valueSelector != null)
{
return valueSelector(attr);
}
return default(TValue);
}
Usage: var someController = new SomeController(Some params); var str = typeof(SomeController).GetControllerMethodAttributeValue(x => someController.SomeMethod(It.IsAny()), (RouteAttribute routeAttribute) => routeAttribute.Template);
Building on @Waterscroll's response, if you want to use async and await in node 8+:
const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';
async function toRun() {
try {
const files = await readdir(directory);
const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
return Promise.all(unlinkPromises);
} catch(err) {
console.log(err);
}
}
toRun();
Others have mentioned the architecture differences (little - big endian).
I read the problem that since the memory for the variables is shared, then by writing to one, the others change and, depending on their type, the value could be meaningless.
eg. union{ float f; int i; } x;
Writing to x.i would be meaningless if you then read from x.f - unless that is what you intended in order to look at the sign, exponent or mantissa components of the float.
I think there is also an issue of alignment: If some variables must be word aligned then you might not get the expected result.
eg. union{ char c[4]; int i; } x;
If, hypothetically, on some machine a char had to be word aligned then c[0] and c[1] would share storage with i but not c[2] and c[3].
I was having the same problem while developing my own website. While it was resident locally, resources opened as file//
. For pages from the internet, including my own loaded as http://
, the F12 Developer did use Edge as default, but not while they were loaded into IE11 from local files.
After following the suggestions above, I unchecked the box for "Display intranet Sites in Compatibility View".
That did the trick without adding any extra coding to my web page, or adding a multitude of pages to populate the list. Now all local files open in Edge document mode with F12.
So if you are referring to using F12 for locally hosted files, this may help.
Style sheets are, effectively, concatenated into a single style sheet in the order in which they appear in the HTML source.
The normal rules for applying rulesets then apply (i.e. by specificity with the last ruleset that defines a given property winning in the event of a tie and !important throwing a spanner into the works)
- What is the difference between connection and read timeout for sockets?
The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read
call, a read timeout error will be raised.
- What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?
It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt()
call may also do the trick ... not sure.)
- What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?
It means that a call to read
on the socket stream may block for ever. Once again there is no infinite loop, but the read
can be unblocked by a Thread.interrupt()
call, closing the socket, and (of course) the other end sending data or closing the connection.
1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.
If you want to parse using InputStreams
public Object xmlToObject(String xmlDataString) {
Object converted = null;
try {
JAXBContext jc = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
converted = unmarshaller.unmarshal(stream);
} catch (JAXBException e) {
e.printStackTrace();
}
return converted;
}
Referring to the first thread / another possibility VS cant open or find pdb file of the process is when you have your executable running in the background. I was working with mpiexec and ran into this issue. Always check your task manager and kill any exec process that your gonna build in your project. Once I did that, it debugged or built fine.
Also, if you try to continue with the warning , the breakpoints would not be hit and it would not have the current executable
Try setting the definer for the function!
So instead of
CREATE FUNCTION get_pet_owner
you will write something akin to
CREATE DEFINER=
procadmin
@%
FUNCTION get_pet_owner
which ought to work if the user prodacmin has rights to create functions/procedures.
In my case the function worked when generated through MySQL Workbench but did not work when run directly as an SQL script. Making the changes above fixed the problem.
This answer uses the DataFrame.filter method to do this without list comprehension:
import pandas as pd
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6]}
df = pd.DataFrame(data)
print(df.filter(like='spike').columns)
Will output just 'spike-2'. You can also use regex, as some people suggested in comments above:
print(df.filter(regex='spike|spke').columns)
Will output both columns: ['spike-2', 'hey spke']
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
With xc8 you have to be careful about declaring a variable
as the same type in each file as you could , erroneously,
declare something an int
in one file and a char
say in another.
This could lead to corruption of variables.
This problem was elegantly solved in a microchip forum some 15 years ago /* See "http:www.htsoft.com" / / "forum/all/showflat.php/Cat/0/Number/18766/an/0/page/0#18766"
But this link seems to no longer work...
So I;ll quickly try to explain it; make a file called global.h.
In it declare the following
#ifdef MAIN_C
#define GLOBAL
/* #warning COMPILING MAIN.C */
#else
#define GLOBAL extern
#endif
GLOBAL unsigned char testing_mode; // example var used in several C files
Now in the file main.c
#define MAIN_C 1
#include "global.h"
#undef MAIN_C
This means in main.c the variable will be declared as an unsigned char
.
Now in other files simply including global.h will have it declared as an extern for that file.
extern unsigned char testing_mode;
But it will be correctly declared as an unsigned char
.
The old forum post probably explained this a bit more clearly.
But this is a real potential gotcha
when using a compiler
that allows you to declare a variable in one file and then declare it extern as a different type in another. The problems associated with
that are if you say declared testing_mode as an int in another file
it would think it was a 16 bit var and overwrite some other part of ram, potentially corrupting another variable. Difficult to debug!
So, I ran into a similar problem and chose to solve it this way instead:
invoke-expression
on the new stringExample solution:
& { invoke-expression "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql=`"Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;`" -dest:dbfullsql=`"Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;`",computername=10.10.10.10,username=administrator,password=adminpass`"" }
You need execute permission on your static files directory. Also they need to be chown'ed by your nginx user and group.
In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:
if yourObject is None: # if yourObject == None:
...
if yourString == "": # if yourString.len() == 0:
...
Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.
Anyway, you can have a look at:
My issue was that I left the "mex" onto the end of my web service link.
Instead of "http://yeagertech.com/yeagerte/YeagerTechWcfService.YeagerTechWcfService.svc/mex"
Use "http://yeagertech.com/yeagerte/YeagerTechWcfService.YeagerTechWcfService.svc"
This works:
import { withRouter } from 'react-router-dom';
const SomeComponent = withRouter(({ history }) => (
<div onClick={() => history.push('/path/some/where')}>
some clickable element
</div>);
);
export default SomeComponent;
By default, on Linux, Pip installs packages to /usr/local/lib/python2.7/dist-packages.
Using virtualenv or --user during install will change this default location. If you use pip show
make sure you are using the right user or else pip
may not see the packages you are referencing.
In c#, View.BringSubviewToFront(childView); YourView.Layer.ZPosition = 1; both should work.
I order to change the dialog buttons and background colors, you will need to extend the Dialog theme, eg.:
<style name="MyDialogStyle" parent="android:Theme.Material.Light.Dialog.NoActionBar">
<item name="android:buttonBarButtonStyle">@style/MyButtonsStyle</item>
<item name="android:colorBackground">@color/white</item>
</style>
<style name="MyButtonsStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">@color/light.blue</item>
</style>
After that, you need to pass this custom style to the dialog builder, eg. like this:
AlertDialog.Builder(requireContext(), R.style.MyDialogStyle)
If you want to change the color of the text inside the dialog, you can pass a custom view to this Builder:
AlertDialog.Builder.setView(View)
or
AlertDialog.Builder.setView(@LayoutResource int)
https://www.electronjs.org/apps/asarui
UI for Asar, Extract All, or drag extract file/directory
In addition to the nested scrolling NestedScrollView
added one major functionality, which could even make it interesting outside of nested contexts: It has build in support for OnScrollChangeListener
. Adding a OnScrollChangeListener
to the original ScrollView
below API 23 required subclassing ScrollView
or messing around with the ViewTreeObserver
of the ScrollView
which often means even more work than subclassing. With NestedScrollView
it can be done using the build-in setter.
For Windows Platform:
try Running the 64 Bit exe version of IntelliJ from a path similar to following.
note that it is available beside the default idea.exe
"C:\Program Files (x86)\JetBrains\IntelliJ IDEA 15.0\bin\idea64.exe"
go get github.com/mattn/sudo
Then
sudo Example1Server.exe
Just print it as an hexadecimal number:
int i = /* ... */;
std::cout << std::hex << i;
Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an =
as true
.
With an example:
// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else
var _GET = (function() {
var _get = {};
var re = /[?&]([^=&]+)(=?)([^&]*)/g;
while (m = re.exec(location.search))
_get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
return _get;
})();
console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123
Also you may have a UniCode non-breaking space xA0...
String[] elements = s.split("[\\s\\xA0]+"); //include uniCode non-breaking
list.append
returns None
, since it is an in-place operation and you are assigning it back to dates_dict[key]
. So, the next time when you do dates_dict.get(key, []).append
you are actually doing None.append
. That is why it is failing. Instead, you can simply do
dates_dict.setdefault(key, []).append(date)
But, we have collections.defaultdict
for this purpose only. You can do something like this
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)
This will create a new list object, if the key
is not found in the dictionary.
Note: Since the defaultdict
will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.
It's because you haven't declared outchar
before you use it. That means that the compiler will assume it's a function returning an int
and taking an undefined number of undefined arguments.
You need to add a prototype pf the function before you use it:
void outchar(char); /* Prototype (declaration) of a function to be called */ int main(void) { ... } void outchar(char ch) { ... }
Note the declaration of the main
function differs from your code as well. It's actually a part of the official C specification, it must return an int
and must take either a void
argument or an int
and a char**
argument.
Building on BrainCore's answer:
int index = 0;
str = "223232-1.jpg";
//Assuming we trust str isn't null
if (str.Contains('-') == "true")
{
int index = str.IndexOf('-');
}
if(index > 0) {
return str.Substring(0, index);
}
else {
return str;
}
You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
convert your inputs to ints:
width = int(input())
height = int(input())
The difference is that when using --mirror
, all refs are copied as-is. This means everything: remote-tracking branches, notes, refs/originals/* (backups from filter-branch). The cloned repo has it all. It's also set up so that a remote update will re-fetch everything from the origin (overwriting the copied refs). The idea is really to mirror the repository, to have a total copy, so that you could for example host your central repo in multiple places, or back it up. Think of just straight-up copying the repo, except in a much more elegant git way.
The new documentation pretty much says all this:
--mirror
Set up a mirror of the source repository. This implies
--bare
. Compared to--bare
,--mirror
not only maps local branches of the source to local branches of the target, it maps all refs (including remote branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by agit remote update
in the target repository.
My original answer also noted the differences between a bare clone and a normal (non-bare) clone - the non-bare clone sets up remote tracking branches, only creating a local branch for HEAD
, while the bare clone copies the branches directly.
Suppose origin has a few branches (master (HEAD)
, next
, pu
, and maint
), some tags (v1
, v2
, v3
), some remote branches (devA/master
, devB/master
), and some other refs (refs/foo/bar
, refs/foo/baz
, which might be notes, stashes, other devs' namespaces, who knows).
git clone origin-url
(non-bare): You will get all of the tags copied, a local branch master (HEAD)
tracking a remote branch origin/master
, and remote branches origin/next
, origin/pu
, and origin/maint
. The tracking branches are set up so that if you do something like git fetch origin
, they'll be fetched as you expect. Any remote branches (in the cloned remote) and other refs are completely ignored.
git clone --bare origin-url
: You will get all of the tags copied, local branches master (HEAD)
, next
, pu
, and maint
, no remote tracking branches. That is, all branches are copied as is, and it's set up completely independent, with no expectation of fetching again. Any remote branches (in the cloned remote) and other refs are completely ignored.
git clone --mirror origin-url
: Every last one of those refs will be copied as-is. You'll get all the tags, local branches master (HEAD)
, next
, pu
, and maint
, remote branches devA/master
and devB/master
, other refs refs/foo/bar
and refs/foo/baz
. Everything is exactly as it was in the cloned remote. Remote tracking is set up so that if you run git remote update
all refs will be overwritten from origin, as if you'd just deleted the mirror and recloned it. As the docs originally said, it's a mirror. It's supposed to be a functionally identical copy, interchangeable with the original.
var o = {
r: 'some value',
t: 'some other value'
};
is functionally equivalent to
var o = new Object();
o.r = 'some value';
o.t = 'some other value';
All DDL statements in Oracle PL/SQL should use Execute Immediate before the statement. Hence you should use:
execute immediate 'truncate table schema.tablename';
There is a project called Locutus, it implements PHP functions in Javascript and in_array() is included, you can use it exactly as you use in PHP.
Examples of use:
in_array('van', myArray);
in_array(1, otherArray, true); // Forcing strict type
To delete rows empty in table
syntax:
DELETE FROM table_name
WHERE column_name IS NULL;
example:
Table name: data ---> column name: pkdno
DELETE FROM data
WHERE pkdno IS NULL;
Answer: 5 rows deleted. (sayso)
The same as @neobot's answer but a little more modern and succinct.
>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'
IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();
int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
MessageBox.show(i);
--Here i want to get the index or current row from the list
}
++i;
}
The most obvious to me would be:
np.any(my_array[:, 0] == value)
In the question above the right answer would be to use Mock
, or to be more precise create_autospec
(because it will add spec to the mock methods of the class you are mocking), the defined spec
on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some
from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch
class MyClass:
@staticmethod
def method(foo, bar):
print(foo)
def something(some_class: MyClass):
arg = 1
# Would fail becuase of wrong parameters passed to methd.
return some_class.method(arg)
def second(some_class: MyClass):
arg = 1
return some_class.unexisted_method(arg)
class TestSomethingTestCase(TestCase):
def test_something_with_autospec(self):
mock = create_autospec(MyClass)
mock.method.return_value = True
# Fails because of signature misuse.
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_something(self):
mock = Mock() # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
mock.method.return_value = True
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
class TestSecondTestCase(TestCase):
def test_second_with_autospec(self):
mock = Mock(spec=MyClass)
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second(self):
mock = Mock()
mock.unexisted_method.return_value = True
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
The test cases with defined spec used fail because methods called from something
and second
functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock
will display.
As a side note there is one more option: use patch.object to mock just the class method which is called with.
The good use cases for patch would be the case when the class is used as inner part of function:
def something():
arg = 1
return MyClass.method(arg)
Then you will want to use patch as a decorator to mock the MyClass.
A refinement on the answer by JSmyth:
console.logCopy = console.log.bind(console);
console.log = function()
{
if (arguments.length)
{
var timestamp = new Date().toJSON(); // The easiest way I found to get milliseconds in the timestamp
var args = arguments;
args[0] = timestamp + ' > ' + arguments[0];
this.logCopy.apply(this, args);
}
};
This:
.log
You can try this code
Dictionary<string,string> AllFields = new Dictionary<string,string>();
string value = (AllFields.TryGetValue(key, out index) ? AllFields[key] : null);
If the key is not present, it simply returns a null value.
Before increasing the max_connections variable, you have to check how many non-interactive connection you have by running show processlist command.
If you have many sleep connection, you have to decrease the value of the "wait_timeout" variable to close non-interactive connection after waiting some times.
SHOW SESSION VARIABLES LIKE 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout | 28800 |
+---------------+-------+
the value is in second, it means that non-interactive connection still up to 8 hours.
SET session wait_timeout=600; Query OK, 0 rows affected (0.00 sec)
After 10 minutes if the sleep connection still sleeping the mysql or MariaDB drop that connection.
I'm afraid there is no "better" way to get this size, however it's not that much pain.
Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size
:
import numpy as np
import cv2
# ...
def cv_size(img):
return tuple(img.shape[1::-1])
If you're on a terminal / ipython, you can also express it with a lambda:
>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)
Writing functions with def
is not fun while working interactively.
Edit
Originally I thought that using [:2]
was OK, but the numpy shape is (height, width[, depth])
, and we need (width, height)
, as e.g. cv2.resize
expects, so - we must use [1::-1]
. Even less memorable than [:2]
. And who remembers reverse slicing anyway?
My solution: Installing libffi-dev with apt-get didn't help. But this helped: Installing libffi from source and then installing Python 3.8 from source.
My configuration: Ubuntu 16.04 LTS Python 3.8.2
Step by step:
I got the error message "ModuleNotFoundError: No module named '_ctypes'" when starting the debugger from Visual Studio Code, and when running python3 -c "import sklearn; sklearn.show_versions()"
.
sudo apt-get install libtool
The file README.md from libffi mentions that autoconf and automake are also necessary. They were already installed on my system../configure --disable-docs
make check
sudo make install
./configure
make
make test
make install
After that my python installation could find _ctypes.
There is!
SLEEP <seconds>
If you want it in millisecond mode:
SLEEP -m <time in milliseconds>
This is more helpful than TIMEOUT
because TIMEOUT
can be aborted with a click of a key or CTRL + C
(for TIMEOUT /t <secs> /nobreak
). SLEEP
cannot be aborted by anything (except for close button :p)
Other one is PING
. But PING
needs internet connection because you'll be recording the connection of a site.
From that you can see that calendar.month_name[3]
would return March
, and the array index of 0
is the empty string, so there's no need to worry about zero-indexing either.
http://www.appinventor.mit.edu/
Creating an App Inventor app begins in your browser, where you design how the app will look. Then, like fitting together puzzle pieces, you set your app's behavior. All the while, through a live connection between your computer and your phone, your app appears on your phone.
You will need separate files for each resolution I am afraid. There is a really good article on campaign monitor describing how they created and implemented their icons for each iOS device too:
http://www.campaignmonitor.com/blog/post/3234/designing-campaign-monitor-ios-icons/
I tried the callback way and could not get this to work, what you have to understand is that values are still atomic even though execution is not. For example:
alert('1');
<--- these two functions will be executed at the same time
alert('2');
<--- these two functions will be executed at the same time
but doing like this will force us to know the order of execution:
loop=2;
total=0;
for(i=0;i<loop;i++) {
total+=1;
if(total == loop)
alert('2');
else
alert('1');
}
My favorite function for entropy is the following:
def entropy(labels):
prob_dict = {x:labels.count(x)/len(labels) for x in labels}
probs = np.array(list(prob_dict.values()))
return - probs.dot(np.log2(probs))
I am still looking for a nicer way to avoid the dict -> values -> list -> np.array conversion. Will comment again if I found it.
2015 update with dplyr:
df %>% group_by(dive) %>% summarise(percentage = mean(speed))
Source: local data frame [2 x 2]
dive percentage
1 dive1 0.4777462
2 dive2 0.6726483
NOW()
returns 2009-08-05 15:13:00
CURDATE()
returns 2009-08-05
CURTIME()
returns 15:13:00
settings.json
.settings.json
> Edit in settings.json
%APPDATA%\Code\User\settings.json
{
"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
"terminal.integrated.shellArgs.windows": ["/k nodevars.bat"]
}
The better way is to include it in a rake task. Create import.rake file inside /lib/tasks/ and put this code to that file.
desc "Imports a CSV file into an ActiveRecord table"
task :csv_model_import, [:filename, :model] => [:environment] do |task,args|
lines = File.new(args[:filename], "r:ISO-8859-1").readlines
header = lines.shift.strip
keys = header.split(',')
lines.each do |line|
values = line.strip.split(',')
attributes = Hash[keys.zip values]
Module.const_get(args[:model]).create(attributes)
end
end
After that run this command in your terminal rake csv_model_import[file.csv,Name_of_the_Model]
Simple way is to use the EJS template engine for serving .html files. Put this line right next to your view engine setup:
app.engine('html', require('ejs').renderFile);
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
This are to way to bind add too numbers
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script>_x000D_
_x000D_
var app = angular.module("myApp", []);_x000D_
_x000D_
app.controller("myCtrl", function($scope) {_x000D_
$scope.total = function() { _x000D_
return parseInt($scope.num1) + parseInt($scope.num2) _x000D_
}_x000D_
})_x000D_
</script>_x000D_
<body ng-app='myApp' ng-controller='myCtrl'>_x000D_
_x000D_
<input type="number" ng-model="num1">_x000D_
<input type="number" ng-model="num2">_x000D_
Total:{{num1+num2}}_x000D_
_x000D_
Total: {{total() }}_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
I've found in www.laughing-buddha.net/php/lib/dirlist/ a function that returns an array containing a list of a directory's contents.
Also look at php.net http://es.php.net/manual/es/ref.filesystem.php where you'll find additional functions for working with files in php.
It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
Both works. Instead of ==
you can write eq
you can define it with using global or GLOBAL, nodejs supports both.
for e.g
global.underscore = require("underscore");
or
GLOBAL.underscore = require("underscore");
Here is the typical structure of new Codeigniter project:
- application/
- system/
- user_guide/
- index.php <- this is the file you need to change
I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.
With this code you can deploy your site to your production server without changing index.php each time.
// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
if (defined('ENVIRONMENT')) {
switch (ENVIRONMENT) {
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
ini_set('display_errors', 0);
break;
default:
exit('The application environment is not set correctly.');
}
}
This works in Cygwin but it should be effective in Linux as well.
ps -W | awk '/ruby/,NF=1' | xargs kill -f
or
ps -W | awk '$0~z,NF=1' z=ruby | xargs kill -f
The cleanest way to fix this is to apply the vertical-align: top
property to you CSS rules:
#div1 div {
width:30px;height:30px;
border:blue 1px solid;
display:inline-block;
*display:inline;zoom:1;
margin:0px;outline:none;
vertical-align: top;
}
If you were to add content to your div
's, then using either line-height: 0
or font-size: 0
would cause problems with your text layout.
See fiddle: http://jsfiddle.net/audetwebdesign/eJqaZ/
This problem can arise when a browser is in "quirks" mode. In this example, changing the doctype from:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
to
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
will change how the browser deals with extra whitespace.
In quirks mode, the whitespace is ignored, but preserved in strict mode.
References:
https://developer.mozilla.org/en/Images,_Tables,_and_Mysterious_Gaps
bit long, it works i guess...
prices = [5, 12, 45]
names = []
for i, _ in enumerate(prices):
names.append("price"+str(i+1))
dict = {}
for name, price in zip(names, prices):
dict[name] = price
for item in dict:
print(item, "=", dict[item])
Swift has a very clear, specific sequence of operations that are done in initializers. Let's start with some basic examples and work our way up to a general case.
Let's take an object A. We'll define it as follows.
class A {
var x: Int
init(x: Int) {
self.x = x
}
}
Notice that A does not have a superclass, so it cannot call a super.init() function as it does not exist.
OK, so now let's subclass A with a new class named B.
class B: A {
var y: Int
init(x: Int, y: Int) {
self.y = y
super.init(x: x)
}
}
This is a departure from Objective-C where [super init]
would typically be called first before anything else. Not so in Swift. You are responsible for ensuring that your instance variables are in a consistent state before you do anything else, including calling methods (which includes your superclass' initializer).
Quickest and easiest way is to use the 'at' command:
ssh user@target "at now -f /home/foo.sh"
Since you are explicitly also asking to handle columns that haven't yet been filled out, and I assume also don't want to mess with them if they have a word instead of a number, you might consider this:
=If(IsNumber(K23), If(K23 > 0, ........., 0), 0)
This just says... If K23 is a number; And if that number is greater than zero; Then do something ......... Otherwise, return zero.
In ........., you might put your division equation there, such as A1/K23
, and you can rest assured that K23 is a number which is greater than zero.
HTML
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick = "SetTarget();" />
Javascript:
function SetTarget() {
document.forms[0].target = "_blank";}
AND codebehind:
Response.Redirect(URL);
The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.
The easiest solution would be to close the file after you've read it in, then reopen it for writing.
with open("replayScript.json", "r") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
with open("replayScript.json", "w") as jsonFile:
json.dump(data, jsonFile)
Alternatively, you can use seek()
to move the cursor back to the beginning of the file then start writing, followed by a truncate()
to deal with the case where the new data is smaller than the previous.
with open("replayScript.json", "r+") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
jsonFile.seek(0) # rewind
json.dump(data, jsonFile)
jsonFile.truncate()
Solving this using Vim editor
cd <path_to_your_directory>
). Ex: cd /home/vineeshvs/work
.vim <file_name>
). Ex: vim myfile.txt
.:set hlsearch
):<line_number>
). Ex: :53
in Vim editor after pressing ESC button once.:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc
). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc
after pressing ESC button once). This process is interactive. You may give y
to replace the tab with spaces and n
to skip a particular replacement. Press ESC when you are done with the required replacements.The easiest way is to call onCreate(null);
and your activity will be like new.
You can get the file name, but you can also get the full path, depending what you place between the '%~' and the '0'. Take your pick from
d -- drive
p -- path
n -- file name
x -- extension
f -- full path
E.g., from inside c:\tmp\foo.bat, %~nx0
gives you "foo.bat", whilst %~dpnx0
gives "c:\tmp\foo.bat". Note the pieces are always assembled in canonical order, so if you get cute and try %~xnpd0
, you still get "c:\tmp\foo.bat"
For those who created rating bar programmatically and want set small rating bar instead of default big rating bar
private LinearLayout generateRatingView(float value){ LinearLayout linearLayoutRating=new LinearLayout(getContext()); linearLayoutRating.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); linearLayoutRating.setGravity(Gravity.CENTER); RatingBar ratingBar = new RatingBar(getContext(),null, android.R.attr.ratingBarStyleSmall); ratingBar.setEnabled(false); ratingBar.setStepSize(Float.parseFloat("0.5"));//for enabling half star ratingBar.setNumStars(5); ratingBar.setRating(value); linearLayoutRating.addView(ratingBar); return linearLayoutRating; }
The div
tag is a block element, causing that behavior.
You should use a span
element instead, which is inline.
If you really want to use div
, add style="display: inline"
. (You can also put that in a CSS rule)
As already mentioned, HTTP itself doesn't impose any hard-coded limit on request length; but browsers have limits ranging on the 2048 character allowed in the GET method.
new File("path_to_file").toURI().toURL();
Date
has the time part, so we only need to extract it from Date
I personally prefer the default format
parameter of the Date
when date and time needs to be separated instead of using the extra SimpleDateFormat
Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")
println "datePart : " + datePart + "\ttimePart : " + timePart
Just go to web.config file and add following
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="Path of your Page" />
</files>
</defaultDocument>
</system.webServer>
Just Simple Set the style attribute of ID:
To Show the hidden div
<div id="xyz" style="display:none">
...............
</div>
//In JavaScript
document.getElementById('xyz').style.display ='block'; // to hide
To hide the shown div
<div id="xyz">
...............
</div>
//In JavaScript
document.getElementById('xyz').style.display ='none'; // to display
For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):
To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is
${basedir}/src/test/resources
. At this point you would have a project directory structure that would look like the following:my-app |-- pom.xml `-- src |-- main | |-- java | | `-- com | | `-- mycompany | | `-- app | | `-- App.java | `-- resources | `-- META-INF | |-- application.properties `-- test |-- java | `-- com | `-- mycompany | `-- app | `-- AppTest.java `-- resources `-- test.properties
In a unit test you could use a simple snippet of code like the following to access the resource required for testing:
... // Retrieve resource InputStream is = getClass().getResourceAsStream("/test.properties" ); // Do something with the resource ...
Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];
To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.
Here is a more easy solution. just remove the "navbar-nav" class and add "nav-justified".
It is simpler than I thought it would be.
To set the font size of the x-axis ticks:
x_ticks=['x tick 1','x tick 2','x tick 3']
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
To do it for the y-axis ticks:
y_ticks=['y tick 1','y tick 2','y tick 3']
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)
The arguments rotation
and fontsize
can easily control what I was after.
Reference: http://matplotlib.org/api/axes_api.html
The HTC devices have the PCSII.apk
which allow them to select usb connect mode. For your device, you can set it manually:
Use SQLite Editor to open /data/data/com.android.providers.setting/databases/settings.db
open table secure
turn settings starting with mount_ums_
to 0, then restart devices.
UPDATE: If it still doesn't work, try turning on debug mode.
There are two points to considerate.
1) This source code worked for me:
private static string Execute(string credentials, string scriptDir, string scriptFilename)
{
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.WorkingDirectory = scriptDir;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.FileName = "sqlplus";
process.StartInfo.Arguments = string.Format("{0} @{1}", credentials, scriptFilename);
process.StartInfo.CreateNoWindow = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return output;
}
I set the working directory to the script directory, so that sub scripts within the script also work.
Call it e.g. as Execute("usr/pwd@service", "c:\myscripts", "script.sql")
2) You have to finalize your SQL script with the statement EXIT;
With Bash (not POSIX) you can use process substitution to get the current line inside a variable. This enables you to use quotes to escape special characters:
while read line ; do cp "$line" ~/bar ; done < <(find . | grep foo)
You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href
.
Example:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
window.location.href = 'https://website.com/my-account';
}
};
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
One problem is, that the compiler does not know, which kind of value is delivered by your function; is assumes, that the function returns an int
in this case, but this can be as correct as it can be wrong. Another problem is, that the compiler does not know, which kind of arguments your function expects, and cannot warn you, if you are passing values of the wrong kind. There are special "promotion" rules, which apply when passing, say floating point values to an undeclared function (the compiler has to widen them to type double), which is often not, what the function actually expects, leading to hard to find bugs at run-time.
If someone want to run it in PowerShell it works like below,
Run Powershell as Administrator
Then
setx /M PATH "$Env:PATH;<path to add>"
To verify, open another Powershell and view PATH as below,
$Env:PATH
If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces
still configured for eth0.
Diagnose:
ethtool -i eth0
Cannot get driver information: no such device
Find your interfaces:
ls /sys/class/net
eth1 eth2 lo
Fix it:
Edit /etc/networking/interfaces
and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)
:%s/eth0/eth2/g
you need to download and install jdk
from here
If try to print the f object, then you will see that there is f.object that can be probed for getting the selected item (applicable for all rails version > 2.3)
logger.warn("f #{f.object.inspect}")
so, use the following script to get the proper selected option:
:selected => f.object.your_field
This is slightly an edge case but I think it can add some value to the other answers.
If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.
For instance the following script:
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line
Will give you this figure, which is wrong:
While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);
# do potentially more stuff here
h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)
This is what you'll get:
If you know how to launch your program from the command line then you can run it from the platformio-ide-terminal
package's terminal. See platformio-ide-terminal
provides an embedded terminal within the Atom text editor. So you can issue commands, including commands to run your Java program, from within it. To install this package you can use APM with the command:
$ apm install platformio-ide-terminal --no-confirm
Alternatively, you can install it from the command palette with:
platformio-ide-terminal
. You have a single quotes conflict, so use:
echo "A,B,C" | sed "s/,/','/g"
If using bash, you can do too (<<<
is a here-string
):
sed "s/,/','/g" <<< "A,B,C"
but not
sed "s/,/','/g" "A,B,C"
because sed
expect file(s) as argument(s)
EDIT:
if you use ksh or any other ones :
echo string | sed ...
Using JQuery you can disable scrolling bar with this code :
$('body').on({
'mousewheel': function(e) {
if (e.target.id == 'el') return;
e.preventDefault();
e.stopPropagation();
}
});
Also you can enable it again with this code :
$('body').unbind('mousewheel');
I seconded Matthieu answer
I commented #Listen 443 in httpd-ssl file and apache can be started
Because the file already has VirtualHost default:443
Apache commons StringEscapeUtils.escapeEcmaScript(String)
returns a string with unicode characters escaped using the \u
notation.
"Art of Beer " -> "Art of Beer \u1F3A8 \u1F37A"
I did not like having to add in the 1 second stall to all of the PerformanceCounter
solutions. Instead I chose to use a WMI
solution. The reason the 1 second wait/stall exists is to allow the reading to be accurate when using a PerformanceCounter
. However if you calling this method often and refreshing this information, I'd advise not to constantly have to incur that delay... even if thinking of doing an async process to get it.
I started with the snippet from here Returning CPU usage in WMI using C# and added a full explanation of the solution on my blog post below:
First, you need to create your branch locally
git checkout -b your_branch
After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it
git push -u origin your_branch
Your Teammates/colleagues can push to your branch by doing commits and then push explicitly
... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch
You can use this:
curl_setopt_array($ch, $options);
$resultado = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info["url"]);
grep
matches, grep -v
does the inverse. If you need to "match A but not B" you usually use pipes:
grep "${PATT}" file | grep -v "${NOTPATT}"
When writing HTML source code, you can define attributes on your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.
For instance, this HTML element:
<input type="text" value="Name:">
has 2 attributes (type
and value
).
Once the browser parses this code, a HTMLInputElement object will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.
For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes
property of that object.
When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it's not a one-to-one relationship. For instance, for this HTML element:
<input id="the-input" type="text" value="Name:">
the corresponding DOM node will have id
,type
, and value
properties (among others):
The id
property is a reflected property for the id
attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. id
is a pure reflected property, it doesn't modify or limit the value.
The type
property is a reflected property for the type
attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. type
isn't a pure reflected property because it's limited to known values (e.g., the valid types of an input). If you had <input type="foo">
, then theInput.getAttribute("type")
gives you "foo"
but theInput.type
gives you "text"
.
In contrast, the value
property doesn't reflect the value
attribute. Instead, it's the current value of the input. When the user manually changes the value of the input box, the value
property will reflect this change. So if the user inputs "John"
into the input box, then:
theInput.value // returns "John"
whereas:
theInput.getAttribute('value') // returns "Name:"
The value
property reflects the current text-content inside the input box, whereas the value
attribute contains the initial text-content of the value
attribute from the HTML source code.
So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute. Or you can use the defaultValue
property, which is a pure reflection of the value
attribute:
theInput.value // returns "John"
theInput.getAttribute('value') // returns "Name:"
theInput.defaultValue // returns "Name:"
There are several properties that directly reflect their attribute (rel
, id
), some are direct reflections with slightly-different names (htmlFor
reflects the for
attribute, className
reflects the class
attribute), many that reflect their attribute but with restrictions/modifications (src
, href
, disabled
, multiple
), and so on. The spec covers the various kinds of reflection.
If you're using Android Studio you can:
You will see a list of all Languages and if you choose them you will see Specific Regions for each. You can also type in the list to filter languages.
Go into your project.
install Gradle.
https://docs.gradle.org/current/userguide/installation.html
On a mac: brew install gradle
Then gradle build --stacktrace
Just for clarification: a table can have at most one primary key. A primary key consists of one or more columns (from that table). If a primary key consists of two or more columns it is called a composite primary key. It is defined as follows:
CREATE TABLE voting (
QuestionID NUMERIC,
MemberID NUMERIC,
PRIMARY KEY (QuestionID, MemberID)
);
The pair (QuestionID,MemberID) must then be unique for the table and neither value can be NULL. If you do a query like this:
SELECT * FROM voting WHERE QuestionID = 7
it will use the primary key's index. If however you do this:
SELECT * FROM voting WHERE MemberID = 7
it won't because to use a composite index requires using all the keys from the "left". If an index is on fields (A,B,C) and your criteria is on B and C then that index is of no use to you for that query. So choose from (QuestionID,MemberID) and (MemberID,QuestionID) whichever is most appropriate for how you will use the table.
If necessary, add an index on the other:
CREATE UNIQUE INDEX idx1 ON voting (MemberID, QuestionID);
The <Comment>
tag contains two text nodes and two <br>
nodes as children.
Your xpath expression was
//*[contains(text(),'ABC')]
To break this down,
*
is a selector that matches any element (i.e. tag) -- it returns a node-set.[]
are a conditional that operates on each individual node in that node set. It matches if any of the individual nodes it operates on match the conditions inside the brackets.text()
is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.contains
is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order. Hence, it can match only the first text node in your <Comment>
element -- namely BLAH BLAH BLAH
. Since that doesn't match, you don't get a <Comment>
in your results.You need to change this to
//*[text()[contains(.,'ABC')]]
*
is a selector that matches any element (i.e. tag) -- it returns a node-set.[]
are a conditional that operates on each individual node in that node set -- here it operates on each element in the document.text()
is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.[]
are a conditional that operates on each node in that node set -- here each individual text node. Each individual text node is the starting point for any path in the brackets, and can also be referred to explicitly as .
within the brackets. It matches if any of the individual nodes it operates on match the conditions inside the brackets.contains
is a function that operates on a string. Here it is passed an individual text node (.
). Since it is passed the second text node in the <Comment>
tag individually, it will see the 'ABC'
string and be able to match it.(in the following code, you should substitute 'UTC'
for zone and now()
for timestamp)
timestamp AT TIME ZONE zone
- SQL-standard-conformingtimezone(zone, timestamp)
- arguably more readableThe function timezone(zone, timestamp) is equivalent to the SQL-conforming construct timestamp AT TIME ZONE zone.
'UTC'
) or as an interval (e.g., INTERVAL '-08:00'
) - here is a list of all available time zonesnow()
returns a value of type timestamp (just what we need) with your database's default time zone attached (e.g. 2018-11-11T12:07:22.3+05:00
).timezone('UTC', now())
turns our current time (of type timestamp with time zone) into the timezonless equivalent in UTC
.SELECT timestamp with time zone '2020-03-16 15:00:00-05' AT TIME ZONE 'UTC'
will return 2020-03-16T20:00:00Z
.Docs: timezone()
You may be tempted to use memcmp(&a, &b, sizeof(struct foo))
, but it may not work in all situations. The compiler may add alignment buffer space to a structure, and the values found at memory locations lying in the buffer space are not guaranteed to be any particular value.
But, if you use calloc
or memset
the full size of the structures before using them, you can do a shallow comparison with memcmp
(if your structure contains pointers, it will match only if the address the pointers are pointing to are the same).
Two things worth pointing out:
You should configure the compiler plugin to compile to at least java 1.5 to handle the annotations when building with Maven. (Can also affect IDE settings, though Eclipse doesn't tend to care.)
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
After that, reconfiguring your project from Maven should fix it. I don't recall exactly how to do that in Eclipse, but you should find it if you right click the project node and poke around the menus.
Here's the function I use:
template<typename T>
static void setValue(T arr[], size_t length, const T& val)
{
std::fill(arr, arr + length, val);
}
template<typename T, size_t N>
static void setValue(T (&arr)[N], const T& val)
{
std::fill(arr, arr + N, val);
}
You can call it like this:
//fixed arrays
int a[10];
setValue(a, 0);
//dynamic arrays
int *d = new int[length];
setValue(d, length, 0);
Above is more C++11 way than using memset. Also you get compile time error if you use dynamic array with specifying the size.
Knockout's documentation also mentions a much cleaner way of passing extra parameters to functions bound using an on-click
binding using function.bind like this:
<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">
Click me
</button>
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
Tested xcode 8 stable version ; Need to use var request
variable with URLRequest()
With thats you can easily fix that (bug)
var request = URLRequest(url:myUrl!)
And
let task = URLSession.shared().dataTask(with: request as URLRequest) { }
Worked fine ! Thank you guys, i think help many people. !
// create table
var dt = new System.Data.DataTable("tableName");
// create fields
dt.Columns.Add("field1", typeof(int));
dt.Columns.Add("field2", typeof(string));
dt.Columns.Add("field3", typeof(DateTime));
// insert row values
dt.Rows.Add(new Object[]{
123456,
"test",
DateTime.Now
});
The fetchSize
parameter is a hint to the JDBC driver as to many rows to fetch in one go from the database. But the driver is free to ignore this and do what it sees fit. Some drivers, like the Oracle one, fetch rows in chunks, so you can read very large result sets without needing lots of memory. Other drivers just read in the whole result set in one go, and I'm guessing that's what your driver is doing.
You can try upgrading your driver to the SQL Server 2008 version (which might be better), or the open-source jTDS driver.
As suggested by Mark Ransom, I found the right encoding for that problem. The encoding was "ISO-8859-1"
, so replacing open("u.item", encoding="utf-8")
with open('u.item', encoding = "ISO-8859-1")
will solve the problem.
try this
$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd
If you just want to check the type, you can use jQuery's .is() function,
Like in my case I used below,
if($("#id").is("select")) {
alert('Select');
else if($("#id").is("input")) {
alert("input");
}
Even the first answer is absolutely brilliant, you probably want to only run script under sudo.
You have to specify the absolute path like:
sudo /home/user/example.sh
sudo ~/example.sh
(both are working)
THIS WONT WORK!
sudo /bin/sh example.sh
sudo example.sh
It will always return
sudo: bin/sh: command not found
sudo: example.sh: command not found
Try this
Sub Txt2Col()
Dim rng As Range
Set rng = [C7]
Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))
rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings
Update: button click event to act on another sheet
Private Sub CommandButton1_Click()
Dim rng As Range
Dim sh As Worksheet
Set sh = Worksheets("Sheet2")
With sh
Set rng = .[C7]
Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))
rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True,
Space:=False,
Other:=False, _
FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
TrailingMinusNumbers:=True
End With
End Sub
Note the .
's (eg .Range
) they refer to the With
statement object
int maxAge = context.Persons.Max(p => p.Age);
This version, if the list is empty:
null
- for nullable overloadsSequence contains no element
exception - for non-nullable overloads-
int maxAge = context.Persons.Select(p => p.Age).DefaultIfEmpty(0).Max();
This version handles the empty list case, but it generates more complex query, and for some reason doesn't work with EF Core.
-
int maxAge = context.Persons.Max(p => (int?)p.Age) ?? 0;
This version is elegant and performant (simple query and single round-trip to the database), works with EF Core. It handles the mentioned exception above by casting the non-nullable type to nullable and then applying the default value using the ??
operator.
Piggybacking on what the other answers say, since you don't know how to do them at all, here's an example of how you might do it in JavaScript:
var charactersOnly = "This contains only characters";
var nonCharacters = "This has _@#*($()*@#$(*@%^_(#@!$ non-characters";
if (charactersOnly.search(/[^a-zA-Z]+/) === -1) {
alert("Only characters");
}
if (nonCharacters.search(/[^a-zA-Z]+/)) {
alert("There are non characters.");
}
The /
starting and ending the regular expression signify that it's a regular expression. The search
function takes both strings and regexes, so the /
are necessary to specify a regex.
From the MDN Docs, the function returns -1
if there is no match.
Also note: that this works for only a-z, A-Z. If there are spaces, it will fail.
Marc Charbonneau wrote:
Keep in mind that @"%d" will only work on 32 bit. Once you start using NSInteger for compatibility if you ever compile for a 64 bit platform, you should use @"%ld" as your format specifier.
Interesting, thanks for the tip, I was using @"%d" with my NSInteger
s!
The SDK documentation also recommends to cast NSInteger
to long
in this case (to match the @"%ld"), e.g.:
NSInteger i = 42;
label.text = [NSString stringWithFormat:@"%ld", (long)i];
Source: String Programming Guide for Cocoa - String Format Specifiers (Requires iPhone developer registration)