In your AndroidManifest.xml add this two-line.
android:usesCleartextTraffic="true"
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
See this below code
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity android:name=".activity.SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
</application>
var table;
$(document).ready(function() {
//datatables
table = $('#userTable').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
"aaSorting": [],
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo base_url().'admin/ajax_list';?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ ], //first column / numbering column
"orderable": false, //set not orderable
},
],
});
});
set
"targets": [0]
to
"targets": [ ]
The aoColumnDefs' aTargets parameter lets you give indexes offset from the right (use a negative number) as well as from the left. So you could do:
aoColumnDefs: [
{
bSortable: false,
aTargets: [ -1 ]
}
]
The equivalent new API (for DataTables 1.10+) would be:
columnDefs: [
{ orderable: false, targets: -1 }
]
Why don't you do:
$("#radio1, #radio2, #radio3, #radio4").checked = false;
Of course, you have to use to tags to do that. One to create the circle and other for the text.
Here some code may help you
#circle {
background: #f00;
width: 200px;
height: 200px;
border-radius: 50%;
color:black;
}
.innerTEXT{
position:absolute;
top:80px;
left:60px;
}
<div id="circle">
<span class="innerTEXT"> Here a text</span>
</div>
Live example here http://jsbin.com/apumik/1/edit
Update
Here less smaller with a few changes
For float
have a look at sys.float_info
:
>>> import sys
>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2
250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsil
on=2.2204460492503131e-16, radix=2, rounds=1)
Specifically, sys.float_info.max
:
>>> sys.float_info.max
1.7976931348623157e+308
If that's not big enough, there's always positive infinity:
>>> infinity = float("inf")
>>> infinity
inf
>>> infinity / 10000
inf
The long
type has unlimited precision, so I think you're only limited by available memory.
Another clean way to do it is to define a private method which create instance et persist concerned Model.
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('label', 256);
$table->timestamps();
$table->softDeletes();
});
$this->postCreate('admin', 'user');
}
private function postCreate(string ...$roles) {
foreach ($roles as $role) {
$model = new Role();
$model->setAttribute('label', $role);
$model->save();
}
}
With this solution, timestamps fields will be generated by Eloquent.
EDIT: it's better to use seeder system to disctinct database structure generation and database population.
Try this
#include <stdio.h>
struct context;
struct funcptrs{
void (*func0)(struct context *ctx);
void (*func1)(void);
};
struct context{
struct funcptrs fps;
};
void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }
void getContext(struct context *con){
con->fps.func0 = func0;
con->fps.func1 = func1;
}
int main(int argc, char *argv[]){
struct context c;
c.fps.func0 = func0;
c.fps.func1 = func1;
getContext(&c);
c.fps.func0(&c);
getchar();
return 0;
}
For simple process watching use watch
instead
argstream
is quite similar to boost.program_option
: it permits to bind variables to options, etc. However it does not handle options stored in a configuration file.
You can use a very nice tool called Stetho
by adding this to build.gradle
file:
compile 'com.facebook.stetho:stetho:1.4.1'
And initialized it inside your Application
or Activity
onCreate()
method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Stetho.initializeWithDefaults(this);
setContentView(R.layout.activity_main);
}
Then you can view the db records in chrome in the address:
chrome://inspect/#devices
For more details you can read my post: How to view easily your db records
function a(a, b) {
return a + b
};
function call_a() {
return a.apply(a, Array.prototype.slice.call(arguments, 0));
}
console.log(call_a(1, 2))
console: 3
I got this solution and it is working for me
if (myNewDT.MyDateTime == null)
{
myNewDT.MyDateTime = DateTime.Now();
}
Another UDF which is hopefully generic enough and does not make assumptions about whether you want to round to a specific number of decimal places:
CREATE FUNCTION [dbo].[fn_FormatNumber] (@number decimal(38,18))
RETURNS varchar(50)
BEGIN
-- remove minus sign before applying thousands seperator
DECLARE @negative bit
SET @negative = CASE WHEN @number < 0 THEN 1 ELSE 0 END
SET @number = ABS(@number)
-- add thousands seperator for every 3 digits to the left of the decimal place
DECLARE @pos int, @result varchar(50) = CAST(@number AS varchar(50))
SELECT @pos = CHARINDEX('.', @result)
WHILE @pos > 4
BEGIN
SET @result = STUFF(@result, @pos-3, 0, ',')
SELECT @pos = CHARINDEX(',', @result)
END
-- remove trailing zeros
WHILE RIGHT(@result, 1) = '0'
SET @result = LEFT(@result, LEN(@result)-1)
-- remove decimal place if not required
IF RIGHT(@result, 1) = '.'
SET @result = LEFT(@result, LEN(@result)-1)
IF @negative = 1
SET @result = '-' + @result
RETURN @result
END
For Android Studio 3.5, fount it using instructions here: https://developer.android.com/studio/debug/device-file-explorer (View -> Tool Windows -> Device File Explorer -> -> databases
@Controller
public class HomeController {
@RequestMapping(method = RequestMethod.GET, value = "/")
public ModelAndView welcome() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login.html");
return modelAndView;
}
}
This will return the Login.html File. The Login.html should be inside the static Folder.
Note: thymeleaf dependency is not added
@RestController
public class HomeController {
@RequestMapping(method = RequestMethod.GET, value = "/")
public String welcome() {
return "login";
}
}
This will return the String login
Application.Exit
End
will work like a charm The "END" immediately terminates further execution while "Application.Exit" closes all forms and calls.
Best regrads,
/* START --- scroll till anchor */
(function($) {
$.fn.goTo = function() {
var top_menu_height=$('#div_menu_header').height() + 5 ;
//alert ( 'top_menu_height is:' + top_menu_height );
$('html, body').animate({
scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px'
}, 500);
return this; // for chaining...
}
})(jQuery);
$(document).ready(function(){
var url = document.URL, idx = url.indexOf("#") ;
var hash = idx != -1 ? url.substring(idx+1) : "";
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var anchor_to_scroll_to = location.hash.replace('#','');
if ( anchor_to_scroll_to != '' ) {
anchor_to_scroll_to = '#' + anchor_to_scroll_to ;
$(anchor_to_scroll_to).goTo();
}
});
});
/* STOP --- scroll till anchror */
I would do this:
std::string a("Hello ");
std::string b("World");
std::string c = a + b;
Which compiles in VS2008.
Since Facebook's Android SDK v4.0 you need to execute the following:
LoginManager.getInstance().logOut();
This is not sufficient. This will simply clear cached access token and profile so that AccessToken.getCurrentAccessToken()
and Profile.getCurrentProfile()
will now become null.
To completely logout you need to revoke permissions and then call LoginManager.getInstance().logOut();
. To revoke permission execute following graph API -
GraphRequest delPermRequest = new GraphRequest(AccessToken.getCurrentAccessToken(), "/{user-id}/permissions/", null, HttpMethod.DELETE, new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse graphResponse) {
if(graphResponse!=null){
FacebookRequestError error =graphResponse.getError();
if(error!=null){
Log.e(TAG, error.toString());
}else {
finish();
}
}
}
});
Log.d(TAG,"Executing revoke permissions with graph path" + delPermRequest.getGraphPath());
delPermRequest.executeAsync();
If you can get SSH to it you can an SSH Port-forwarded SVN server.
Use SSHs -L
( or -R
, I forget, it always confuses me ) to make an ssh tunnel so that
127.0.0.1:3690
is really connecting to remote:3690 over the ssh tunnel, and then you can use it via
svn co svn://127.0.0.1/....
to remove the Text from backbutton programmatically, used below Code this will work form xcode7 and above.
self.navigationController.navigationBar.topItem.title = @" ";
or
manualLy in storyboards, select the navigation bar on the view controller and put " " in back button text.
this will work. thanks
I had Python 2.7 installed via chocolatey on Windows and found pip2.7.exe
in C:\tools\python2\Scripts
.
Using this executable instead of the pip
command installed the correct module for me (requests
for Python 2.7).
Odd errors like "inappropriate ioctl for device" are usually a result of checking $! at some point other than just after a system call failed. If you'd show your code, I bet someone would rapidly point out your error.
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
Let's say in Swift 4 you have a button set up for a segue as an IBAction
like this @IBAction func nextLevel(_ sender: UIButton) {}
and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:
var appMode = 0
@IBAction func mySegue(_ sender: UIButton) {
if appMode == 1 { // avoid crash if button pressed during other app actions and/or conditions
let conflictingAction = sender as UIButton
conflictingAction.isEnabled = false
}
}
Please note that you will likely have other conditions within if appMode == 0
and/or if appMode == 1
that will still occur and NOT conflict with the mySegue
button. Thus, AVOIDING A CRASH.
Think of it as Java's answer to the PATH environment variable - OSes search for EXEs on the PATH, Java searches for classes and packages on the classpath.
Caling .Value2
is an expensive operation because it's a COM-interop call. I would instead read the entire range into an array and then loop through the array:
object[,] data = Range.Value2;
// Create new Column in DataTable
for (int cCnt = 1; cCnt <= Range.Columns.Count; cCnt++)
{
textBox3.Text = cCnt.ToString();
var Column = new DataColumn();
Column.DataType = System.Type.GetType("System.String");
Column.ColumnName = cCnt.ToString();
DT.Columns.Add(Column);
// Create row for Data Table
for (int rCnt = 1; rCnt <= Range.Rows.Count; rCnt++)
{
textBox2.Text = rCnt.ToString();
string CellVal = String.Empty;
try
{
cellVal = (string)(data[rCnt, cCnt]);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
{
ConvertVal = (double)(data[rCnt, cCnt]);
cellVal = ConvertVal.ToString();
}
DataRow Row;
// Add to the DataTable
if (cCnt == 1)
{
Row = DT.NewRow();
Row[cCnt.ToString()] = cellVal;
DT.Rows.Add(Row);
}
else
{
Row = DT.Rows[rCnt + 1];
Row[cCnt.ToString()] = cellVal;
}
}
}
The two functions do vastly different things!
The resize()
method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect the size()
, iteration will go over all those elements, push_back will insert after them and you can directly access them using the operator[]
.
The reserve()
method only allocates memory, but leaves it uninitialized. It only affects capacity()
, but size()
will be unchanged. There is no value for the objects, because nothing is added to the vector. If you then insert the elements, no reallocation will happen, because it was done in advance, but that's the only effect.
So it depends on what you want. If you want an array of 1000 default items, use resize()
. If you want an array to which you expect to insert 1000 items and want to avoid a couple of allocations, use reserve()
.
EDIT: Blastfurnace's comment made me read the question again and realize, that in your case the correct answer is don't preallocate manually. Just keep inserting the elements at the end as you need. The vector will automatically reallocate as needed and will do it more efficiently than the manual way mentioned. The only case where reserve()
makes sense is when you have reasonably precise estimate of the total size you'll need easily available in advance.
EDIT2: Ad question edit: If you have initial estimate, then reserve()
that estimate. If it turns out to be not enough, just let the vector do it's thing.
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
This worked for me
mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name
should probably be
mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name
you can apply two commands
git diff --patch > mypatch.patch // to generate the patch
git apply mypatch.patch // to apply the patch
here is an example script using file -I and iconv which works on MacOsX For your question you need to use mv instead of iconv
#!/bin/bash
# 2016-02-08
# check encoding and convert files
for f in *.java
do
encoding=`file -I $f | cut -f 2 -d";" | cut -f 2 -d=`
case $encoding in
iso-8859-1)
iconv -f iso8859-1 -t utf-8 $f > $f.utf8
mv $f.utf8 $f
;;
esac
done
I think Heuristic is more of a constraint used in Learning Based Model in Artificial Intelligent since the future solution states are difficult to predict.
But then my doubt after reading above answers is "How would Heuristic can be successfully applied using Stochastic Optimization Techniques? or can they function as full fledged algorithms when used with Stochastic Optimization?"
what about this
--// Convert NVARCHAR to DATETIME
DECLARE @date DATETIME = (SELECT convert(DATETIME, '2013-08-29 13:55:48', 120))
--// Convert DATETIME to custom NVARCHAR FORMAT
SELECT
RIGHT('00'+ CAST(DAY(@date) AS NVARCHAR),2) + '-' +
RIGHT('00'+ CAST(MONTH(@date) AS NVARCHAR),2) + '-' +
CAST(YEAR(@date) AS NVARCHAR) + ' ' +
CAST(CONVERT(TIME,@date) AS NVARCHAR)
result: '29-08-2013 13:55:48.0000000'
For users of IntelliJ IDEA or Android Studio make these steps:
* From the menu Build/Generate signed APK
* You need to create a keystore path. From the dialog click Create new
. You will create a jks file that includes your keys. Select folder, define a password. So your keystore ok.
* Create new key by for your application by using alias, key password, your name etc.
* Click next.
* From the dialog either select Proguard or not.
Your signed APK file is ready.
Help file: https://www.jetbrains.com/idea/webhelp/generate-signed-apk-wizard.html
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
@Petr Mensik & kensen john
Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:
<%
String callback = request.getParameter("callback");
response.setCharacterEncoding("UTF-8");
if (callback != null) {
// Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
response.setContentType("text/javascript");
} else {
// Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
response.setContentType("application/json");
}
[...]
String output = "";
if (callback != null) {
output += callback + "(";
}
output += jsonObj.toString();
if (callback != null) {
output += ");";
}
%>
<%=output %>
When callback is supplied, returns:
callback({...JSON stuff...});
with content-type "text/javascript"
When callback is NOT supplied, returns:
{...JSON stuff...}
with content-type "application/json"
As described in the API of java.sql.PreparedStatement.setBinaryStream()
it is available since 1.6 so it is a JDBC 4.0 API! You use a JDBC 3 Driver so this method is not available!
You will have to specify a fixed height, you cannot use 100% because there is nothing for this to be compared to, as in height=100%
of what?
Edited fiddle:
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
Why think? If not
confuses you, switch your if and else clauses around to avoid the negation.
i want to make sure that ( u0 <= u < u0+step ) before do sth.
Just write that.
if u0 <= u < u0+step:
"do sth" # What language is "sth"? No vowels. An odd-looking word.
else:
u0 = u0+ step
Why overthink it?
If you need an empty if
-- and can't work out the logic -- use pass
.
if some-condition-that's-too-complex-for-me-to-invert:
pass
else:
do real work here
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);
Context
can be your current Activity
.
You can plot multiple subplots of multiple pandas data frames using matplotlib with a simple trick of making a list of all data frame. Then using the for loop for plotting subplots.
Working code:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# dataframe sample data
df1 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df2 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df3 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df4 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df5 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df6 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
#define number of rows and columns for subplots
nrow=3
ncol=2
# make a list of all dataframes
df_list = [df1 ,df2, df3, df4, df5, df6]
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
for c in range(ncol):
df_list[count].plot(ax=axes[r,c])
count=+1
Using this code you can plot subplots in any configuration. You need to just define number of rows nrow
and number of columns ncol
. Also, you need to make list of data frames df_list
which you wanted to plot.
Put this in the myhtml.html
file:
<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>
In the same directory make a subscript.js
file and put this in there:
//Use jquery to look up the tag with the id of 'myscript' above. Get
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");
//print filename out to screen.
document.write(filename);
Analyze Result:
Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.
jsfiddle proof that the above works:
You can also use the helper method Exists over the Mongo operator $exists
ME.find()
.exists('pictures')
.where('pictures').ne([])
.sort('-created')
.limit(10)
.exec(function(err, results){
...
});
DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);
The fact the character is a < make me think you have a PHP error, have you tried echoing all errors.
Since I don't have your database, I'm going through your code trying to find errors, so far, I've updated your JS file
$("#register-form").submit(function (event) {
var entrance = $(this).find('input[name="IsValid"]').val();
var password = $(this).find('input[name="objPassword"]').val();
var namesurname = $(this).find('input[name="objNameSurname"]').val();
var email = $(this).find('input[name="objEmail"]').val();
var gsm = $(this).find('input[name="objGsm"]').val();
var adres = $(this).find('input[name="objAddress"]').val();
var termsOk = $(this).find('input[name="objAcceptTerms"]').val();
var formURL = $(this).attr("action");
if (request) {
request.abort(); // cancel if any process on pending
}
var postData = {
"objAskGrant": entrance,
"objPass": password,
"objNameSurname": namesurname,
"objEmail": email,
"objGsm": parseInt(gsm),
"objAdres": adres,
"objTerms": termsOk
};
$.post(formURL,postData,function(data,status){
console.log("Data: " + data + "\nStatus: " + status);
});
event.preventDefault();
});
PHP Edit:
if (isset($_POST)) {
$fValid = clear($_POST['objAskGrant']);
$fTerms = clear($_POST['objTerms']);
if ($fValid) {
$fPass = clear($_POST['objPass']);
$fNameSurname = clear($_POST['objNameSurname']);
$fMail = clear($_POST['objEmail']);
$fGsm = clear(int($_POST['objGsm']));
$fAddress = clear($_POST['objAdres']);
$UserIpAddress = "hidden";
$UserCityLocation = "hidden";
$UserCountry = "hidden";
$DateTime = new DateTime();
$result = $date->format('d-m-Y-H:i:s');
$krr = explode('-', $result);
$resultDateTime = implode("", $krr);
$data = array('error' => 'Yükleme Sirasinda Hata Olustu');
$kayit = "INSERT INTO tbl_Records(UserNameSurname, UserMail, UserGsm, UserAddress, DateAdded, UserIp, UserCityLocation, UserCountry, IsChecked, GivenPasscode) VALUES ('$fNameSurname', '$fMail', '$fGsm', '$fAddress', '$resultDateTime', '$UserIpAddress', '$UserCityLocation', '$UserCountry', '$fTerms', '$fPass')";
$retval = mysql_query( $kayit, $conn ); // Update with you connection details
if ($retval) {
$data = array('success' => 'Register Completed', 'postData' => $_POST);
}
} // valid ends
}echo json_encode($data);
ruby on rails notes has a very nice blogpost about commenting in erb-files
the short version is
to comment a single line use
<%# commented line %>
to comment a whole block use a if false
to surrond your code like this
<% if false %>
code to comment
<% end %>
You can start IPython session from pudb and go back to the debugging session as you like.
BTW, ipdb is using IPython behind the scenes and you can actually use IPython functionality such as TAB completion and magic commands (the one starts with %
). If you are OK with ipdb you can start it from IPython using commands such as %run
and %debug
. ipdb session is actually better than plain IPython one in the sense you can go up and down in the stack trace etc. What is missing in ipdb for "object inspection"?
Also, python.el bundled with Emacs >= 24.3 has nice ipdb support.
The error message:
merge: remote/master - not something we can merge
is saying that Git doesn't recognize remote/master
. This is probably because you don't have a "remote" named "remote". You have a "remote" named "origin".
Think of "remotes" as an alias for the url to your Git server. master
is your locally checked-out version of the branch. origin/master
is the latest version of master
from your Git server that you have fetched (downloaded). A fetch
is always safe because it will only update the "origin/x" version of your branches.
So, to get your master
branch back in sync, first download the latest content from the git server:
git fetch
Then, perform the merge:
git merge origin/master
...But, perhaps the better approach would be:
git pull origin master
The pull
command will do the fetch
and merge
for you in one step.
You state in the comments that the returned JSON is this:
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
You're telling Gson that you have an array of Post
objects:
List<Post> postsList = Arrays.asList(gson.fromJson(reader,
Post[].class));
You don't. The JSON represents exactly one Post
object, and Gson is telling you that.
Change your code to be:
Post post = gson.fromJson(reader, Post.class);
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
You can use MD5() in mysql or md5() in php. To use salt add it to password before running md5, f.e.:
$salt ='my_string';
$hash = md5($salt . $password);
It's better to use different salt for every password. For this you have to save your salt in db (and also hash). While authentication user will send his login and pass. You will find his hash and salt in db and find out:
if ($hash == md5($salt . $_POST['password'])) {}
The only way that worked for me is creating a Boolean variable that I set to true when I add the event. Then I ask: If the variable is false, I add the event.
bool alreadyAdded = false;
This variable can be global.
if(!alreadyAdded)
{
myClass.MyEvent += MyHandler;
alreadyAdded = true;
}
The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher
//Pass results back to the client
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);
How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries?
If using the 4.5+ Framework, there is now the ZipArchive and ZipFile classes.
using (ZipArchive zip = ZipFile.Open("test.zip", ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(@"c:\something.txt", "data/path/something.txt");
}
You need to add references to:
For .NET Core targeting net46, you need to add dependencies for
Example project.json:
"dependencies": {
"System.IO.Compression": "4.1.0",
"System.IO.Compression.ZipFile": "4.0.1"
},
"frameworks": {
"net46": {}
}
For .NET Core 2.0, just adding a simple using statement is all that is needed:
To start the process with parameters, you can use following code:
string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);
To kill/exit the program again, you can use following code:
proc.CloseMainWindow();
proc.Close();
This problem is also caused by:
If you are on a mac/linux, and are using 'ControlMaster' in your ~/.ssh/config, there may be some ssh control master processes running.
To find them, run:
ps aux | grep '\[mux\]'
And kill the relevant ones.
You can simply place multiple name together separated by a white space like
C:\Users\Dell>pip install markdown django-filter
#c:\Users\Dell is path in my pc this can be anything on yours
this installed markdown and django-filter on my device.
select convert_tz(now(),@@session.time_zone,'+05:30')
replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994
to format into desired time format, eg:
select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p')
you will get similar to this -> Dec 17 2014 10:39:56 AM
import codecs
f=codecs.open("test.html", 'r')
print f.read()
Try something like this.
Not sure what your desired output is, but if you're using list comprehension, the order follows the order of nested loops, which you have backwards. So I got the what I think you want with:
[float(y) for x in l for y in x]
The principle is: use the same order you'd use in writing it out as nested for loops.
Please note that soultions written above removes only space. If you want also to remove tab or new line use stri_replace_all_charclass
from stringi
package.
library(stringi)
stri_replace_all_charclass(" ala \t ma \n kota ", "\\p{WHITE_SPACE}", "")
## [1] "alamakota"
Use accept attribute with the MIME_type as values
<input type="file" accept="image/gif, image/jpeg" />
String target = "FOOBar";
target = target.replaceAll("(?i)foo", "");
System.out.println(target);
Output:
Bar
It's worth mentioning that replaceAll
treats the first argument as a regex pattern, which can cause unexpected results. To solve this, also use Pattern.quote
as suggested in the comments.
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
Below code changes to 'datetime' type and also formats in the given format string. Works well!
df['DOB']=pd.to_datetime(df['DOB'].dt.strftime('%m/%d/%Y'))
yourimg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
and make sure there is no parent tags with position: relative in it
The below code snippet will help evaluate primitive type holding NaN.
double dbl = Double.NaN;
Double.valueOf(dbl).isNaN() ? true : false;
After I performed the following instructions in SSMS, everything works fine:
create login [IIS APPPOOL\MyWebAPP] from windows;
exec sp_addsrvrolemember N'IIS APPPOOL\MyWebAPP', sysadmin
Make a toggle function in the respective scope to grey out the link.
First,create the following CSS classes in your .css file.
.disabled {
pointer-events: none;
cursor: default;
}
.enabled {
pointer-events: visible;
cursor: auto;
}
Add a $scope.state and $scope.toggle variable. Edit your controller in the JS file like:
$scope.state='on';
$scope.toggle='enabled';
$scope.changeState = function () {
$scope.state = $scope.state === 'on' ? 'off' : 'on';
$scope.toggleEdit();
};
$scope.toggleEdit = function () {
if ($scope.state === 'on')
$scope.toggle = 'enabled';
else
$scope.toggle = 'disabled';
};
Now,in the HTML a tags edit as:
<a href="#" ng-click="create()" class="{{toggle}}">CREATE</a><br/>
<a href="#" ng-click="edit()" class="{{toggle}}">EDIT</a><br/>
<a href="#" ng-click="delete()" class="{{toggle}}">DELETE</a>
To avoid the problem of the link disabling itself, change the DOM CSS class at the end of the function.
document.getElementById("create").className = "enabled";
Here is another implementation of a Unicode CSV parser (works with wchar_t). I wrote part of it, while Jonathan Leffler wrote the rest.
Note: This parser is aimed at replicating Excel's behavior as closely as possible, specifically when importing broken or malformed CSV files.
This is the original question - Parsing CSV file with multiline fields and escaped double quotes
This is the code as a SSCCE (Short, Self-Contained, Correct Example).
#include <stdbool.h>
#include <wchar.h>
#include <wctype.h>
extern const wchar_t *nextCsvField(const wchar_t *p, wchar_t sep, bool *newline);
// Returns a pointer to the start of the next field,
// or zero if this is the last field in the CSV
// p is the start position of the field
// sep is the separator used, i.e. comma or semicolon
// newline says whether the field ends with a newline or with a comma
const wchar_t *nextCsvField(const wchar_t *p, wchar_t sep, bool *newline)
{
// Parse quoted sequences
if ('"' == p[0]) {
p++;
while (1) {
// Find next double-quote
p = wcschr(p, L'"');
// If we don't find it or it's the last symbol
// then this is the last field
if (!p || !p[1])
return 0;
// Check for "", it is an escaped double-quote
if (p[1] != '"')
break;
// Skip the escaped double-quote
p += 2;
}
}
// Find next newline or comma.
wchar_t newline_or_sep[4] = L"\n\r ";
newline_or_sep[2] = sep;
p = wcspbrk(p, newline_or_sep);
// If no newline or separator, this is the last field.
if (!p)
return 0;
// Check if we had newline.
*newline = (p[0] == '\r' || p[0] == '\n');
// Handle "\r\n", otherwise just increment
if (p[0] == '\r' && p[1] == '\n')
p += 2;
else
p++;
return p;
}
static wchar_t *csvFieldData(const wchar_t *fld_s, const wchar_t *fld_e, wchar_t *buffer, size_t buflen)
{
wchar_t *dst = buffer;
wchar_t *end = buffer + buflen - 1;
const wchar_t *src = fld_s;
if (*src == L'"')
{
const wchar_t *p = src + 1;
while (p < fld_e && dst < end)
{
if (p[0] == L'"' && p+1 < fld_s && p[1] == L'"')
{
*dst++ = p[0];
p += 2;
}
else if (p[0] == L'"')
{
p++;
break;
}
else
*dst++ = *p++;
}
src = p;
}
while (src < fld_e && dst < end)
*dst++ = *src++;
if (dst >= end)
return 0;
*dst = L'\0';
return(buffer);
}
static void dissect(const wchar_t *line)
{
const wchar_t *start = line;
const wchar_t *next;
bool eol;
wprintf(L"Input %3zd: [%.*ls]\n", wcslen(line), wcslen(line)-1, line);
while ((next = nextCsvField(start, L',', &eol)) != 0)
{
wchar_t buffer[1024];
wprintf(L"Raw Field: [%.*ls] (eol = %d)\n", (next - start - eol), start, eol);
if (csvFieldData(start, next-1, buffer, sizeof(buffer)/sizeof(buffer[0])) != 0)
wprintf(L"Field %3zd: [%ls]\n", wcslen(buffer), buffer);
start = next;
}
}
static const wchar_t multiline[] =
L"First field of first row,\"This field is multiline\n"
"\n"
"but that's OK because it's enclosed in double quotes, and this\n"
"is an escaped \"\" double quote\" but this one \"\" is not\n"
" \"This is second field of second row, but it is not multiline\n"
" because it doesn't start \n"
" with an immediate double quote\"\n"
;
int main(void)
{
wchar_t line[1024];
while (fgetws(line, sizeof(line)/sizeof(line[0]), stdin))
dissect(line);
dissect(multiline);
return 0;
}
First you need to make sure that jQuery script is loaded. This could be from a CDN or local on your website. If you don't load this first before trying to use jQuery it will tell you that jQuery is not defined.
<script src="jquery.min.js"></script>
This could be in the HEAD or in the footer of the page, just make sure you load it before you try to call any other jQuery stuff.
Then you need to use one of the two solutions below
(function($){
// your standard jquery code goes here with $ prefix
// best used inside a page with inline code,
// or outside the document ready, enter code here
})(jQuery);
or
jQuery(document).ready(function($){
// standard on load code goes here with $ prefix
// note: the $ is setup inside the anonymous function of the ready command
});
please be aware that many times $(document).ready(function(){//code here}); will not work.
Had to solve this myself today. Solved it in C# as I needed it for a program, but I guess it can be esily rewritten. Consider this Public Domain.
public static string GetGitRoot (string file_path) {
file_path = System.IO.Path.GetDirectoryName (file_path);
while (file_path != null) {
if (Directory.Exists (System.IO.Path.Combine (file_path, ".git")))
return file_path;
file_path = Directory.GetParent (file_path).FullName;
}
return null;
}
Try the following commands in terminal, this will work better:
apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.
The following:
.blue-border, .background {
border: 1px solid #00f;
background: #fff;
}
is for when you want to add styles to elements that have either the blue-border or background class, for example:
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
would all get a blue border and white background applied to them.
However, the accepted answer is different.
.blue-border.background {
border: 1px solid #00f;
background: #fff;
}
This applies the styles to elements that have both classes so in this example only the <div>
with both classes should get the styles applied (in browsers that interpret the CSS properly):
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.
To track down the correct parameters you need to go first to ?plot.default
, which refers you to ?par
and ?axis
:
plot(1, 1 ,xlab="x axis", ylab="y axis", pch=19,
col.lab="red", cex.lab=1.5, # for the xlab and ylab
col="green") # for the points
You need to subscribe to a SMS gateway. There are thousands of those (try searching with google) and they are usually not free. For example this one has support for PHP.
$(element).click(function(){
window.close();
});
Note: you can not close any window that you didn't opened with window.open
. Directly invoking window.close()
will ask user with a dialogue box.
Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.
Public Function SendEmail2()
Dim varName As Variant
Dim varCC As Variant
Dim varSubject As Variant
Dim varBody As Variant
varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','
varSubject = "Hello"
'Email subject
varBody = "Let's get ice cream this week"
'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File
End Function
Once CSS Media Queries Level 4 is implemented, you'll be able to do this:
@media (hover: hover) {
button:hover {
background-color: blue;
}
}
Or in English: "If the browser supports proper/true/real/non-emulated hovering (e.g. has a mouse-like primary input device), then apply this style when button
s are hovered over."
Since this part of Media Queries Level 4 has so far only been implemented in bleeding-edge Chrome, I wrote a polyfill to deal with this. Using it, you can transform the above futuristic CSS into:
html.my-true-hover button:hover {
background-color: blue;
}
(A variation on the .no-touch
technique) And then using some client-side JavaScript from the same polyfill that detects support for hovering, you can toggle the presence of the my-true-hover
class accordingly:
$(document).on('mq4hsChange', function (e) {
$(document.documentElement).toggleClass('my-true-hover', e.trueHover);
});
(SELECT column1 as column FROM table )
UNION
(SELECT column2 as column FROM table )
There is a much easier way!
You can easily create an attached DocumentXaml
(or DocumentRTF
) property which will allow you to bind the RichTextBox
's document. It is used like this, where Autobiography
is a string property in your data model:
<TextBox Text="{Binding FirstName}" />
<TextBox Text="{Binding LastName}" />
<RichTextBox local:RichTextBoxHelper.DocumentXaml="{Binding Autobiography}" />
Voila! Fully bindable RichTextBox
data!
The implementation of this property is quite simple: When the property is set, load the XAML (or RTF) into a new FlowDocument
. When the FlowDocument
changes, update the property value.
This code should do the trick:
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
public class RichTextBoxHelper : DependencyObject
{
public static string GetDocumentXaml(DependencyObject obj)
{
return (string)obj.GetValue(DocumentXamlProperty);
}
public static void SetDocumentXaml(DependencyObject obj, string value)
{
obj.SetValue(DocumentXamlProperty, value);
}
public static readonly DependencyProperty DocumentXamlProperty =
DependencyProperty.RegisterAttached(
"DocumentXaml",
typeof(string),
typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
PropertyChangedCallback = (obj, e) =>
{
var richTextBox = (RichTextBox)obj;
// Parse the XAML to a document (or use XamlReader.Parse())
var xaml = GetDocumentXaml(richTextBox);
var doc = new FlowDocument();
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
range.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)),
DataFormats.Xaml);
// Set the document
richTextBox.Document = doc;
// When the document changes update the source
range.Changed += (obj2, e2) =>
{
if (richTextBox.Document == doc)
{
MemoryStream buffer = new MemoryStream();
range.Save(buffer, DataFormats.Xaml);
SetDocumentXaml(richTextBox,
Encoding.UTF8.GetString(buffer.ToArray()));
}
};
}
});
}
The same code could be used for TextFormats.RTF or TextFormats.XamlPackage. For XamlPackage you would have a property of type byte[]
instead of string
.
The XamlPackage format has several advantages over plain XAML, especially the ability to include resources such as images, and it is more flexible and easier to work with than RTF.
It is hard to believe this question sat for 15 months without anyone pointing out the easy way to do this.
I dont know why you havent marked on of these gr8 answers... here is another option which would enable you and anyone else visiting to control transition speed and pause time
JAVASCRIPT
$(function () {
/* SET PARAMETERS */
var change_img_time = 5000;
var transition_speed = 100;
var simple_slideshow = $("#exampleSlider"),
listItems = simple_slideshow.children('li'),
listLen = listItems.length,
i = 0,
changeList = function () {
listItems.eq(i).fadeOut(transition_speed, function () {
i += 1;
if (i === listLen) {
i = 0;
}
listItems.eq(i).fadeIn(transition_speed);
});
};
listItems.not(':first').hide();
setInterval(changeList, change_img_time);
});
.
HTML
<ul id="exampleSlider">
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
</ul>
.
If your keeping this simple its easy to keep it resposive
best to visit the: DEMO
.
If you want something with special transition FX (Still responsive) - check this out
DEMO WITH SPECIAL FX
For the accepted solution to work if your TextInput
is inside another component, you'll need to "pop" the reference from ref
to the parent container.
// MyComponent
render() {
<View>
<TextInput ref={(r) => this.props.onRef(r)} { ...this.props }/>
</View>
}
// MyView
render() {
<MyComponent onSubmitEditing={(evt) => this.myField2.focus()}/>
<MyComponent onRef={(r) => this.myField2 = r}/>
}
At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut
is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.
git remote prune
and git fetch --prune
do the same thing: deleting the refs to the branches that don't exist on the remote, as you said. The second command connects to the remote and fetches its current branches before pruning.
However it doesn't touch the local branches you have checked out, that you can simply delete with
git branch -d random_branch_I_want_deleted
Replace -d
by -D
if the branch is not merged elsewhere
git prune
does something different, it purges unreachable objects, those commits that aren't reachable in any branch or tag, and thus not needed anymore.
For me, the way it worked is I have to kill the parent process. Figure the parent process out and kill it
taskkill /IM "parent_process_name.exe" /T /F
while(node.firstChild) {
node.removeChild(node.firstChild);
}
This should get you for starting with two letters and ending with two numbers.
[A-Za-z]{2}(.*)[0-9]{2}
If you know it will always be just two and two you can
[A-Za-z]{2}[0-9]{2}
For VB.NET developers:
Add the following line to the Glabal.asax.vb file, at the end of method Application_Start()
Database.SetInitializer(Of ApplicationDbContext)(Nothing)
Change ApplicationDbContext to your specific Db context.
detectScrollbarWidthHeight: function() {
var div = document.createElement("div");
div.style.overflow = "scroll";
div.style.visibility = "hidden";
div.style.position = 'absolute';
div.style.width = '100px';
div.style.height = '100px';
document.body.appendChild(div);
return {
width: div.offsetWidth - div.clientWidth,
height: div.offsetHeight - div.clientHeight
};
},
Tested in Chrome, FF, IE8, IE11.
EDIT: as of Java8 you'd better use Files
class:
Path resultingPath = Files.createDirectories('A/B');
I don't know if this ultimately fixes your problem but class File
has method mkdirs()
which fully creates the path specified by the file.
File f = new File("/A/B/");
f.mkdirs();
There are several ways rsync compares files -- the authoritative source is the rsync algorithm description: https://www.andrew.cmu.edu/course/15-749/READINGS/required/cas/tridgell96.pdf. The wikipedia article on rsync is also very good.
For local files, rsync compares metadata and if it looks like it doesn't need to copy the file because size and timestamp match between source and destination it doesn't look further. If they don't match, it cp's the file. However, what if the metadata do match but files aren't actually the same? Then rsync probably didn't do what you intended.
Files that are the same size may still have changed. One simple example is a text file where you correct a typo -- like changing "teh" to "the". The file size is the same, but the corrected file will have a newer timestamp. --size-only
says "don't look at the time; if size matches assume files match", which would be the wrong choice in this case.
On the other hand, suppose you accidentally did a big cp -r A B
yesterday, but you forgot to preserve the time stamps, and now you want to do the operation in reverse rsync B A
. All those files you cp'ed have yesterday's time stamp, even though they weren't really modified yesterday, and rsync will by default end up copying all those files, and updating the timestamp to yesterday too. --size-only
may be your friend in this case (modulo the example above).
--ignore-times
says to compare the files regardless of whether the files have the same modify time. Consider the typo example above, but then not only did you correct the typo but you used touch
to make the corrected file have the same modify time as the original file -- let's just say you're sneaky that way. Well --ignore-times
will do a diff of the files even though the size and time match.
Checkout intent properties like no history , clear back stack etc ... Intent.setFlags
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
Actually, the absolutely easiest way is to do the following...
byte[] content = your_byte[];
FileContentResult result = new FileContentResult(content, "application/octet-stream")
{
FileDownloadName = "your_file_name"
};
return result;
RewriteRule ^(.*)foobar(.*)$ http://www.example.com/index.php [L,R=301]
(No space inside your website)
This is what Sun-Oracle documentation says:
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
If you deal with dates it is a good idea to look at the joda time library for a more sane Date manipulation model.
Build.DEVICE // The name of the industrial design.
Build.DEVICE Gives the human readable name for some devices than Build.MODEL
Build.DEVICE = OnePlus6
Build.MANUFACTURER = OnePlus
Build.MODEL = ONEPLUS A6003
This maybe help somebody who is looking for the way to sort table by two columns, but in paralel way. This means to combine two sorts using aggregate sorting function. It's very useful when for example retrieving articles using fulltext search and also concerning the article publish date.
This is only example, but if you catch the idea you can find a lot of aggregate functions to use. You can even weight the columns to prefer one over second. The function of mine takes extremes from both sorts, thus the most valued rows are on the top.
Sorry if there exists simplier solutions to do this job, but I haven't found any.
SELECT
`id`,
`text`,
`date`
FROM
(
SELECT
k.`id`,
k.`text`,
k.`date`,
k.`match_order_id`,
@row := @row + 1 as `date_order_id`
FROM
(
SELECT
t.`id`,
t.`text`,
t.`date`,
@row := @row + 1 as `match_order_id`
FROM
(
SELECT
`art_id` AS `id`,
`text` AS `text`,
`date` AS `date`,
MATCH (`text`) AGAINST (:string) AS `match`
FROM int_art_fulltext
WHERE MATCH (`text`) AGAINST (:string IN BOOLEAN MODE)
LIMIT 0,101
) t,
(
SELECT @row := 0
) r
ORDER BY `match` DESC
) k,
(
SELECT @row := 0
) l
ORDER BY k.`date` DESC
) s
ORDER BY (1/`match_order_id`+1/`date_order_id`) DESC
You can also use the undocumented sp_MSforeachtable stored procedure as such if you are looking to do this for every table:
sp_MSforeachtable @command1 ="PRINT 'TABLE NAME: ' + '?' DECLARE @RowCount INT SET @RowCount = (SELECT COUNT(*) FROM ?) PRINT @RowCount"
Just the same way as you would do in command console. Copy exactly those commands in the batch file.
If it is a directory you own, grant yourself access to it:
chmod u+rx,go-w openfire
That grants you permission to use the directory and the files in it (x
) and to list the files that are in it (r
); it also denies group and others write permission on the directory, which is usually correct (though sometimes you may want to allow group to create files in your directory - but consider using the sticky bit on the directory if you do).
If it is someone else's directory, you'll probably need some help from the owner to change the permissions so that you can access it (or you'll need help from root
to change the permissions for you).
Please see IIS7 Integrated mode: Request is not available in this context exception in Application_Start:
The “Request is not available in this context” exception is one of the more common errors you may receive on when moving ASP.NET applications to Integrated mode on IIS 7.0. This exception happens in your implementation of the Application_Start method in the global.asax file if you attempt to access the HttpContext of the request that started the application.
If you're using IIS Express, select Show All Application
from IIS Express in the task bar notification area, then select Stop All
.
Now re-run your application.
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
In case anyone else runs into this, I took WhoIsRich's example and modified it a bit. When calling ReadReg I needed to do the following: ReadReg("App", "HKEY_CURRENT_USER\App\Version") which would then be able to read the version number from the registry, if it existed. I also am using HKCU since it does not require admin privileges to write to.
Function ReadReg(RegKey, RegPath)
Const HKEY_CURRENT_USER = &H80000001
Dim objRegistry, oReg
Set objRegistry = CreateObject("Wscript.shell")
Set oReg = GetObject("winmgmts:!root\default:StdRegProv")
if oReg.EnumKey(HKEY_CURRENT_USER, RegKey) = 0 Then
ReadReg = objRegistry.RegRead(RegPath)
else
ReadReg = ""
end if
End Function
For anyone else having the same problem, I figured it out myself.
<html>_x000D_
<body>_x000D_
<form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
<input type="hidden" name="fullname" value="Sam" />_x000D_
<input type="hidden" name="city" value="Dubai " />_x000D_
<input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.
The new git-switch
command (starting in GIT 2.23) also has a flag --discard-changes
which should help you. git pull
might be necessary afterwards.
Warning: it's still considered to be experimental.
AngularJs has "Services" and "Factories" just for problems like yours.These are used to have something global between Controllers, Directives, Other Services or any other angularjs components..You can defined functions, store data, make calculate functions or whatever you want inside Services and use them in AngularJs Components as Global.like
angular.module('MyModule', [...])
.service('MyService', ['$http', function($http){
return {
users: [...],
getUserFriends: function(userId){
return $http({
method: 'GET',
url: '/api/user/friends/' + userId
});
}
....
}
}])
if you need more
Find More About Why We Need AngularJs Services and Factories
I tried using performance.now() to analyze the performance of the different types of loops. I took a very large array and found the sum of all elements of the array. I ran the code three times every time and found forEach and reduce to be a clear winner.
// For loop
let arr = [...Array(100000).keys()]
function addUsingForLoop(ar){
let sum = 0;
for(let i = 0; i < ar.length; i++){
sum += ar[i];
}
console.log(`Sum: ${sum}`);
return sum;
}
let t1 = performance.now();
addUsingForLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)
// "Sum: 4999950000"
// "Time Taken ~ 42.17500000959262 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.41999999107793 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 49.845000030472875 milliseconds"
// While loop
let arr = [...Array(100000).keys()]
function addUsingWhileLoop(ar){
let sum = 0;
let index = 0;
while (index < ar.length) {
sum += ar[index];
index++;
}
console.log(`Sum: ${sum}`)
return sum;
}
let t1 = performance.now();
addUsingWhileLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)
// "Sum: 4999950000"
// "Time Taken ~ 44.2499999771826 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.01999997207895 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 41.71000001952052 milliseconds"
// do-while
let arr = [...Array(100000).keys()]
function addUsingDoWhileLoop(ar){
let sum = 0;
let index = 0;
do {
sum += index;
index++;
} while (index < ar.length);
console.log(`Sum: ${sum}`);
return sum;
}
let t1 = performance.now();
addUsingDoWhileLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)
// "Sum: 4999950000"
// "Time Taken ~ 43.79500000504777 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 43.47500001313165 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 47.535000019706786 milliseconds"
// Reverse loop
let arr = [...Array(100000).keys()]
function addUsingReverseLoop(ar){
var sum=0;
for (var i=ar.length; i--;) {
sum+=arr[i];
}
console.log(`Sum: ${sum}`);
return sum;
}
let t1 = performance.now();
addUsingReverseLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)
// "Sum: 4999950000"
// "Time Taken ~ 46.199999982491136 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.96500000823289 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 43.880000011995435 milliseconds"
// Reverse while loop
let arr = [...Array(100000).keys()]
function addUsingReverseWhileLoop(ar){
var sum = 0;
var i = ar.length;
while (i--) {
sum += ar[i];
}
console.log(`Sum: ${sum}`);
return sum;
}
var t1 = performance.now();
addUsingReverseWhileLoop(arr);
var t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)
// "Sum: 4999950000"
// "Time Taken ~ 46.26999999163672 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 42.97000000951812 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.31500000646338 milliseconds"
// reduce
let arr = [...Array(100000).keys()]
let t1 = performance.now();
sum = arr.reduce((pv, cv) => pv + cv, 0);
console.log(`Sum: ${sum}`)
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)
// "Sum: 4999950000"
// "Time Taken ~ 4.654999997001141 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.040000018198043 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 4.835000028833747 milliseconds"
// forEach
let arr = [...Array(100000).keys()]
function addUsingForEach(ar){
let sum = 0;
ar.forEach(item => {
sum += item;
})
console.log(`Sum: ${sum}`);
return sum
}
let t1 = performance.now();
addUsingForEach(arr)
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)
// "Sum: 4999950000"
// "Time Taken ~ 5.315000016707927 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.869999993592501 mienter code herelliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.405000003520399 milliseconds"
Based on this discussion, I built this config.json
that works perfectly:
{
"development": {
"username": "root",
"password": null,
"logging" : false,
"database": "posts_db_dev",
"host": "127.0.0.1",
"dialect": "mysql",
"operatorsAliases": false
}
}
I found this solution very helpful in a clean way to remove xml configuration entirely.
Please check this db configuration using JNDI and spring framework. http://www.unotions.com/design/how-to-create-oracleothersql-db-configuration-using-spring-and-maven/
By this article, it explain how easy to create a db confguration based on database jndi(db/test) configuration. once you are done with configuration then all the db repositories are loaded using this jndi. I did find useful. If @Pierre has issue with this then let me know. It's complete solution to write db configuration.
Wrap them in an extra pair of parens and you're good to go.
if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == ''))
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
Oh must add my own pick here, you will use this when you encode/decode some string obj you transfer between two programs.
Lets say you use base64encode some array in python, and then you want to decode that into c++. Once you have the string you decode from base64decode in c++. In order to get it back to array of float, all you need to do here is
float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);
This is pretty common use I suppose.
This is the easy way to handle timestamp insertion
$data = array('created_on' => date('Y-m-d H:i:s'));
Just access the first item of the list/array, using the index access and the index 0:
>>> list_ = [4]
>>> list_[0]
4
>>> array_ = np.array([4])
>>> array_[0]
4
This will be an int
since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float()
on it then:
>>> float(list_[0])
4.0
A hacky way of doing JSON_UNESCAPED_UNICODE in PHP 5.3. Really disappointed by PHP json support. Maybe this will help someone else.
$array = some_json();
// Encode all string children in the array to html entities.
array_walk_recursive($array, function(&$item, $key) {
if(is_string($item)) {
$item = htmlentities($item);
}
});
$json = json_encode($array);
// Decode the html entities and end up with unicode again.
$json = html_entity_decode($rson);
for nth highest salary. its easy way
select t.name,t.sal
from (select name,sal,dense_rank() over (order by sal desc) as rank from emp) t
where t.rank=6; //suppose i find 6th highest salary
You can find the answer on this other S.O. question:
MySQL - can I limit the maximum time allowed for a query to run?
a cron job that runs every second on your database server, connecting and doing something like this:
- SHOW PROCESSLIST
- Find all connections with a query time larger than your maximum desired time
- Run KILL [process id] for each of those processes
Inspired by user Brent Self:
lsof -i 4 -a | grep LISTEN
How about: hasattr(a, "__iter__")
?
It tells if the object returned can be iterated over as a generator. By default, tuples and lists can, but not the string types.
I had the same problem and I found this solution working with bindParam :
bindParam(':param', $myvar = NULL, PDO::PARAM_INT);
git stash apply
Just check out the branch you want your changes on, and then git stash apply
. Then use git diff
to see the result.
After you're all done with your changes—the apply
looks good and you're sure you don't need the stash any more—then use git stash drop
to get rid of it.
I always suggest using git stash apply
rather than git stash pop
. The difference is that apply
leaves the stash around for easy re-try of the apply
, or for looking at, etc. If pop
is able to extract the stash, it will immediately also drop
it, and if you the suddenly realize that you wanted to extract it somewhere else (in a different branch), or with --index
, or some such, that's not so easy. If you apply
, you get to choose when to drop
.
It's all pretty minor one way or the other though, and for a newbie to git, it should be about the same. (And you can skip all the rest of this!)
There are at least three or four different "ways to use git stash", as it were. The above is for "way 1", the "easy way":
You started with a clean branch, were working on some changes, and then realized you were doing them in the wrong branch. You just want to take the changes you have now and "move" them to another branch.
This is the easy case, described above. Run git stash save
(or plain git stash
, same thing). Check out the other branch and use git stash apply
. This gets git to merge in your earlier changes, using git's rather powerful merge mechanism. Inspect the results carefully (with git diff
) to see if you like them, and if you do, use git stash drop
to drop the stash. You're done!
You started some changes and stashed them. Then you switched to another branch and started more changes, forgetting that you had the stashed ones.
Now you want to keep, or even move, these changes, and apply your stash too.
You can in fact git stash save
again, as git stash
makes a "stack" of changes. If you do that you have two stashes, one just called stash
—but you can also write stash@{0}
—and one spelled stash@{1}
. Use git stash list
(at any time) to see them all. The newest is always the lowest-numbered. When you git stash drop
, it drops the newest, and the one that was stash@{1}
moves to the top of the stack. If you had even more, the one that was stash@{2}
becomes stash@{1}
, and so on.
You can apply
and then drop
a specific stash, too: git stash apply stash@{2}
, and so on. Dropping a specific stash, renumbers only the higher-numbered ones. Again, the one without a number is also stash@{0}
.
If you pile up a lot of stashes, it can get fairly messy (was the stash I wanted stash@{7}
or was it stash@{4}
? Wait, I just pushed another, now they're 8 and 5?). I personally prefer to transfer these changes to a new branch, because branches have names, and cleanup-attempt-in-December
means a lot more to me than stash@{12}
. (The git stash
command takes an optional save-message, and those can help, but somehow, all my stashes just wind up named WIP on branch
.)
(Extra-advanced) You've used git stash save -p
, or carefully git add
-ed and/or git rm
-ed specific bits of your code before running git stash save
. You had one version in the stashed index/staging area, and another (different) version in the working tree. You want to preserve all this. So now you use git stash apply --index
, and that sometimes fails with:
Conflicts in index. Try without --index.
You're using git stash save --keep-index
in order to test "what will be committed". This one is beyond the scope of this answer; see this other StackOverflow answer instead.
For complicated cases, I recommend starting in a "clean" working directory first, by committing any changes you have now (on a new branch if you like). That way the "somewhere" that you are applying them, has nothing else in it, and you'll just be trying the stashed changes:
git status # see if there's anything you need to commit
# uh oh, there is - let's put it on a new temp branch
git checkout -b temp # create new temp branch to save stuff
git add ... # add (and/or remove) stuff as needed
git commit # save first set of changes
Now you're on a "clean" starting point. Or maybe it goes more like this:
git status # see if there's anything you need to commit
# status says "nothing to commit"
git checkout -b temp # optional: create new branch for "apply"
git stash apply # apply stashed changes; see below about --index
The main thing to remember is that the "stash" is a commit, it's just a slightly "funny/weird" commit that's not "on a branch". The apply
operation looks at what the commit changed, and tries to repeat it wherever you are now. The stash will still be there (apply
keeps it around), so you can look at it more, or decide this was the wrong place to apply
it and try again differently, or whatever.
Any time you have a stash, you can use git stash show -p
to see a simplified version of what's in the stash. (This simplified version looks only at the "final work tree" changes, not the saved index changes that --index
restores separately.) The command git stash apply
, without --index
, just tries to make those same changes in your work-directory now.
This is true even if you already have some changes. The apply
command is happy to apply a stash to a modified working directory (or at least, to try to apply it). You can, for instance, do this:
git stash apply stash # apply top of stash stack
git stash apply stash@{1} # and mix in next stash stack entry too
You can choose the "apply" order here, picking out particular stashes to apply in a particular sequence. Note, however, that each time you're basically doing a "git merge", and as the merge documentation warns:
Running git merge with non-trivial uncommitted changes is discouraged: while possible, it may leave you in a state that is hard to back out of in the case of a conflict.
If you start with a clean directory and are just doing several git apply
operations, it's easy to back out: use git reset --hard
to get back to the clean state, and change your apply
operations. (That's why I recommend starting in a clean working directory first, for these complicated cases.)
Let's say you're doing Lots Of Advanced Git Stuff, and you've made a stash, and want to git stash apply --index
, but it's no longer possible to apply the saved stash with --index
, because the branch has diverged too much since the time you saved it.
This is what git stash branch
is for.
If you:
stash
, thengit stash apply --index
the attempt to re-create the changes definitely will work. This is what git stash branch newbranch
does. (And it then drops the stash since it was successfully applied.)
--index
(what the heck is it?)What the --index
does is simple to explain, but a bit complicated internally:
git add
(or "stage") them before commit
ing.git stash
, you might have edited both files foo
and zorg
, but only staged one of those.git add
s the add
ed things and does not git add
the non-added things. That is, if you add
ed foo
but not zorg
back before you did the stash
, it might be nice to have that exact same setup. What was staged, should again be staged; what was modified but not staged, should again be modified but not staged.The --index
flag to apply
tries to set things up this way. If your work-tree is clean, this usually just works. If your work-tree already has stuff add
ed, though, you can see how there might be some problems here. If you leave out --index
, the apply
operation does not attempt to preserve the whole staged/unstaged setup. Instead, it just invokes git's merge machinery, using the work-tree commit in the "stash bag". If you don't care about preserving staged/unstaged, leaving out --index
makes it a lot easier for git stash apply
to do its thing.
Here is a neat and clean way to install Python2 & Python3 on windows.
My case: I had to install Apache cassandra. I already had Python3 installed in my D: drive. With loads of development work under process i didn't wanted to mess my Python3 installation. And, i needed Python2 only for Apache cassandra.
So i took following steps:
C:\Python27;C:\Python27\Scripts
)So, my Python3 installation remained intact.
In my case it seems the problem was a weird caching problem. The solutions above didn't work.
If your code was working fine and you added a column to one of your tables and it gives the 'invalid column name' error, and the solutions above doesn't work, try this: First run only the section of code for creating that modified table and then run the whole code.
For those who want a straight-forward code example in Java 7:
Dog
class:
package com.mypackage.bean;
public class Dog {
private String name;
private int age;
public Dog() {
// empty constructor
}
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void printDog(String name, int age) {
System.out.println(name + " is " + age + " year(s) old.");
}
}
ReflectionDemo
class:
package com.mypackage.demo;
import java.lang.reflect.*;
public class ReflectionDemo {
public static void main(String[] args) throws Exception {
String dogClassName = "com.mypackage.bean.Dog";
Class<?> dogClass = Class.forName(dogClassName); // convert string classname to class
Object dog = dogClass.newInstance(); // invoke empty constructor
String methodName = "";
// with single parameter, return void
methodName = "setName";
Method setNameMethod = dog.getClass().getMethod(methodName, String.class);
setNameMethod.invoke(dog, "Mishka"); // pass arg
// without parameters, return string
methodName = "getName";
Method getNameMethod = dog.getClass().getMethod(methodName);
String name = (String) getNameMethod.invoke(dog); // explicit cast
// with multiple parameters
methodName = "printDog";
Class<?>[] paramTypes = {String.class, int.class};
Method printDogMethod = dog.getClass().getMethod(methodName, paramTypes);
printDogMethod.invoke(dog, name, 3); // pass args
}
}
Output:
Mishka is 3 year(s) old.
You can invoke the constructor with parameters this way:
Constructor<?> dogConstructor = dogClass.getConstructor(String.class, int.class);
Object dog = dogConstructor.newInstance("Hachiko", 10);
Alternatively, you can remove
String dogClassName = "com.mypackage.bean.Dog";
Class<?> dogClass = Class.forName(dogClassName);
Object dog = dogClass.newInstance();
and do
Dog dog = new Dog();
Method method = Dog.class.getMethod(methodName, ...);
method.invoke(dog, ...);
Suggested reading: Creating New Class Instances
How about:
function changeText() {
$("#demoTable td").each(function () {
$(this).html().replace("8: Tap on APN and Enter <B>www</B>", "");
}
}
you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">
$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');
My mongoose version is 4.10.2
Seems only the hook findOneAndUpdate
is work
ModelSchema.pre('findOneAndUpdate', function(next) {
// console.log('pre findOneAndUpdate ....')
this.update({},{ $set: { updatedAt: new Date() } });
next()
})
Suspend the process with CTRL+Z then use the command bg
to resume it in background. For example:
sleep 60
^Z #Suspend character shown after hitting CTRL+Z
[1]+ Stopped sleep 60 #Message showing stopped process info
bg #Resume current job (last job stopped)
More about job control and bg
usage in bash
manual page:
JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.
EDIT
To start a process where you can even kill the terminal and it still carries on running
nohup [command] [-args] > [filename] 2>&1 &
e.g.
nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &
To just ignore the output (not very wise) change the filename to /dev/null
To get the error message set to a different file change the &1
to a filename.
In addition: You can use the jobs
command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1
or kill %2
with the number being the index of the process.
By using the requestInterceptor, it worked for me:
const ui = SwaggerUIBundle({
...
requestInterceptor: (req) => {
req.headers.Authorization = "Bearer " + req.headers.Authorization;
return req;
},
...
});
First of all, DOS has nothing to do with it, you probably want a Windows command line solution (again: no DOS, pure Windows, just not a Window, but a Console).
You can either use the VBScript method provided by boflynn or you can mis-use net send
or msg
. net send
works only on older versions of windows:
net send localhost Some message to display
This also depends on the Messenger service to run, though.
For newer versions (XP and onward, apparently):
msg "%username%" Some message to display
It should be noted that a message box sent using msg.exe
will only last for 60 seconds. This can however be overridden with the /time:xx
switch.
Another approach, if you simply wish to print a PDF file programmatically, is to use the LPR command: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/lpr.mspx?mfr=true
LPR is available on newer versions of Windows too (e.g. Vista/7), but you need to enable it in the Optional Windows Components.
For example:
Process.Start("LPR -S printerdnsalias -P raw C:\files\file.pdf");
You can also use the printer IP address instead of the alias.
This assumes that your printer supports PDF Direct Printing otherwise this will only work for PostScript and ASCII files. Also, the printer needs to have a network interface installed and you need to know it's IP address or alias.
Clear backstack without loops
String name = getSupportFragmentManager().getBackStackEntryAt(0).getName();
getSupportFragmentManager().popBackStack(name, FragmentManager.POP_BACK_STACK_INCLUSIVE);
Where name is the addToBackStack() parameter
getSupportFragmentManager().beginTransaction().
.replace(R.id.container, fragments.get(titleCode))
.addToBackStack(name)
Here's one:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?lngWId=8&txtCodeId=1786
Another:
function ping($host, $port, $timeout) {
$tB = microtime(true);
$fP = fSockOpen($host, $port, $errno, $errstr, $timeout);
if (!$fP) { return "down"; }
$tA = microtime(true);
return round((($tA - $tB) * 1000), 0)." ms";
}
//Echoing it will display the ping if the host is up, if not it'll say "down".
echo ping("www.google.com", 80, 10);
For versions previous to FreeMarker 2.3.7
You can not use ??
to handle missing values, the old syntax is:
<#if userName?exists>
Hi ${userName}, How are you?
</#if>
TortoiseSVN 1.7 has an option for installing the command line tools.
It isn't checked by default, but you can run the installer again and select it. It will also automatically update your PATH environment variable.
I have fixed in this way
uninstall existing local nodemon
npm uninstall nodemon
install it again globally.
npm i -g nodemon
JavaScript Code
//this function is used to fire click event
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
function showPdf(){
eventFire(document.getElementById('picToClick'), 'click');
}
HTML Code
<img id="picToClick" data-toggle="modal" data-target="#pdfModal" src="img/Adobe-icon.png" ng-hide="1===1">
<button onclick="showPdf()">Click me</button>
Your problem seams to be located here:
SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,LEN(Voucher_No)- LEN(@Prefix)) AS INT)) AS varchar(100)) FROM dbo.Journal_Entry;
SET @sCode=CAST(@maxCode AS INT)
As the error says, you're casting a string that contains a letter 'J' to an INT
which for obvious reasons is not possible.
Either fix SUBSTRING
or don't store the letter 'J' in the database and only prepend it when reading.
You have to use br when using echo , like this :
echo "Thanks for your email" ."<br>". "Your orders details are below:"
and it will work properly
Here is an attempt to get << and >> stream operators on enum automatically with an one line macro command only...
Definitions:
#include <string>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <vector>
#define MAKE_STRING(str, ...) #str, MAKE_STRING1_(__VA_ARGS__)
#define MAKE_STRING1_(str, ...) #str, MAKE_STRING2_(__VA_ARGS__)
#define MAKE_STRING2_(str, ...) #str, MAKE_STRING3_(__VA_ARGS__)
#define MAKE_STRING3_(str, ...) #str, MAKE_STRING4_(__VA_ARGS__)
#define MAKE_STRING4_(str, ...) #str, MAKE_STRING5_(__VA_ARGS__)
#define MAKE_STRING5_(str, ...) #str, MAKE_STRING6_(__VA_ARGS__)
#define MAKE_STRING6_(str, ...) #str, MAKE_STRING7_(__VA_ARGS__)
#define MAKE_STRING7_(str, ...) #str, MAKE_STRING8_(__VA_ARGS__)
#define MAKE_STRING8_(str, ...) #str, MAKE_STRING9_(__VA_ARGS__)
#define MAKE_STRING9_(str, ...) #str, MAKE_STRING10_(__VA_ARGS__)
#define MAKE_STRING10_(str) #str
#define MAKE_ENUM(name, ...) MAKE_ENUM_(, name, __VA_ARGS__)
#define MAKE_CLASS_ENUM(name, ...) MAKE_ENUM_(friend, name, __VA_ARGS__)
#define MAKE_ENUM_(attribute, name, ...) name { __VA_ARGS__ }; \
attribute std::istream& operator>>(std::istream& is, name& e) { \
const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
std::string str; \
std::istream& r = is >> str; \
const size_t len = sizeof(name##Str)/sizeof(name##Str[0]); \
const std::vector<std::string> enumStr(name##Str, name##Str + len); \
const std::vector<std::string>::const_iterator it = std::find(enumStr.begin(), enumStr.end(), str); \
if (it != enumStr.end())\
e = name(it - enumStr.begin()); \
else \
throw std::runtime_error("Value \"" + str + "\" is not part of enum "#name); \
return r; \
}; \
attribute std::ostream& operator<<(std::ostream& os, const name& e) { \
const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
return (os << name##Str[e]); \
}
Usage:
// Declare global enum
enum MAKE_ENUM(Test3, Item13, Item23, Item33, Itdsdgem43);
class Essai {
public:
// Declare enum inside class
enum MAKE_CLASS_ENUM(Test, Item1, Item2, Item3, Itdsdgem4);
};
int main() {
std::cout << Essai::Item1 << std::endl;
Essai::Test ddd = Essai::Item1;
std::cout << ddd << std::endl;
std::istringstream strm("Item2");
strm >> ddd;
std::cout << (int) ddd << std::endl;
std::cout << ddd << std::endl;
}
Not sure about the limitations of this scheme though... comments are welcome!
Another reasonably straightforward way is to use regular expressions and sub
:
sub('.*(?=.$)', '', string, perl=T)
So, "get rid of everything followed by one character". To grab more characters off the end, add however many dots in the lookahead assertion:
sub('.*(?=.{2}$)', '', string, perl=T)
where .{2}
means ..
, or "any two characters", so meaning "get rid of everything followed by two characters".
sub('.*(?=.{3}$)', '', string, perl=T)
for three characters, etc. You can set the number of characters to grab with a variable, but you'll have to paste
the variable value into the regular expression string:
n = 3
sub(paste('.+(?=.{', n, '})', sep=''), '', string, perl=T)
function Index($index) {
$Count = count($YOUR_ARRAY);
if ($index <= $Count) {
$Keys = array_keys($YOUR_ARRAY);
$Value = array_values($YOUR_ARRAY);
return $Keys[$index] . ' = ' . $Value[$index];
} else {
return "Out of the ring";
}
}
echo 'Index : ' . Index(0);
Replace the ( $YOUR_ARRAY )
turn on display errors in your ini
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
Immutable Object's state cannot be altered.
for example String
.
String str= "abc";//a object of string is created
str = str + "def";// a new object of string is created and assigned to str
install tensorflow by running these commands in anoconda shell or in console:
conda create -n tensorflow python=3.5
activate tensorflow
conda install pandas matplotlib jupyter notebook scipy scikit-learn
pip install tensorflow
close the console and reopen it and type these commands:
activate tensorflow
jupyter notebook
As Danack said in comments, there are 2 php.ini files. I uncommented the line with curl extension in the one in Apache folder, which is php.ini used by the web server.
Composer, on the other hand, uses php for console which is a whole different story. Php.ini file for that program is not the one in Apache folder but it's in the PHP folder and I had to uncomment the line in it too. Then I ran the installation again and it was OK.
Nowadays with HTML5, it's pretty simple:
<input type="search" placeholder="Search..."/>
Most modern browsers will automatically render a usable clear button in the field by default.
(If you use Bootstrap, you'll have to add an override to your css file to make it show)
input[type=search]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
Safari/WebKit browsers can also provide extra features when using type="search"
, like results=5
and autosave="..."
, but they also override many of your styles (e.g. height, borders) . To prevent those overrides, while still retaining functionality like the X button, you can add this to your css:
input[type=search] {
-webkit-appearance: none;
}
See css-tricks.com for more info about the features provided by type="search"
.
You can stop a macro by pressing ctrl + break but if you don't have the break key you could use this autohotkey (open source) code:
+ESC:: SendInput {CtrlBreak} return
Pressing shift + Escape will be like pressing ctrl + break and thus will stop your macro.
All the glory to this page
Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.
I know this is an old question, but I just stumbled across the thread and there seems to be a conflation here between errors and rejection that runs afoul (in many cases, at least) of the oft-repeated advice not to use exception handling to deal with anticipated cases. To illustrate: if an async method is trying to authenticate a user and the authentication fails, that's a rejection (one of two anticipated cases) and not an error (e.g., if the authentication API was unavailable.)
To make sure I wasn't just splitting hairs, I ran a performance test of three different approaches to that, using this code:
const iterations = 100000;
function getSwitch() {
return Math.round(Math.random()) === 1;
}
function doSomething(value) {
return 'something done to ' + value.toString();
}
let processWithThrow = function () {
if (getSwitch()) {
throw new Error('foo');
}
};
let processWithReturn = function () {
if (getSwitch()) {
return new Error('bar');
} else {
return {}
}
};
let processWithCustomObject = function () {
if (getSwitch()) {
return {type: 'rejection', message: 'quux'};
} else {
return {type: 'usable response', value: 'fnord'};
}
};
function testTryCatch(limit) {
for (let i = 0; i < limit; i++) {
try {
processWithThrow();
} catch (e) {
const dummyValue = doSomething(e);
}
}
}
function testReturnError(limit) {
for (let i = 0; i < limit; i++) {
const returnValue = processWithReturn();
if (returnValue instanceof Error) {
const dummyValue = doSomething(returnValue);
}
}
}
function testCustomObject(limit) {
for (let i = 0; i < limit; i++) {
const returnValue = processWithCustomObject();
if (returnValue.type === 'rejection') {
const dummyValue = doSomething(returnValue);
}
}
}
let start, end;
start = new Date();
testTryCatch(iterations);
end = new Date();
const interval_1 = end - start;
start = new Date();
testReturnError(iterations);
end = new Date();
const interval_2 = end - start;
start = new Date();
testCustomObject(iterations);
end = new Date();
const interval_3 = end - start;
console.log(`with try/catch: ${interval_1}ms; with returned Error: ${interval_2}ms; with custom object: ${interval_3}ms`);
Some of the stuff that's in there is included because of my uncertainty regarding the Javascript interpreter (I only like to go down one rabbit hole at a time); for instance, I included the doSomething
function and assigned its return to dummyValue
to ensure that the conditional blocks wouldn't get optimized out.
My results were:
with try/catch: 507ms; with returned Error: 260ms; with custom object: 5ms
I know that there are plenty of cases where it's not worth the trouble to hunt down small optimizations, but in larger-scale systems these things can make a big cumulative difference, and that's a pretty stark comparison.
SO… while I think the accepted answer's approach is sound in cases where you're expecting to have to handle unpredictable errors within an async function, in cases where a rejection simply means "you're going to have to go with Plan B (or C, or D…)" I think my preference would be to reject using a custom response object.
You can also try this:
var data= _.reverse(_.sortBy(res.locals.subscriptionList.items, ['type', 'name']));
Just in case there is someone out there who's a bit new like me, double check that you are spelling your header folders correctly.
For example:
<#include "Component/BoxComponent.h"
This will result in the error. Instead, it needs to be:
<#include "Components/BoxComponent.h"
Under Windows 10 OS environment, the following method works for me:
https://github.com/tesseract-ocr/tesseract/wiki Download tesseract and install it. Windows version is available here: https://github.com/UB-Mannheim/tesseract/wiki
Find script file pytesseract.py from C:\Users\User\Anaconda3\Lib\site-packages\pytesseract and open it.
Change the following code from tesseract_cmd = 'tesseract'
to: tesseract_cmd = 'D:/Program Files (x86)/Tesseract-OCR/tesseract.exe'
You may also need add environment variable D:/Program Files (x86)/Tesseract-OCR/
Hope it works for you!
Generating strings from (for example) lowercase characters:
import random, string
def randomword(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
Results:
>>> randomword(10)
'vxnxikmhdc'
>>> randomword(10)
'ytqhdohksy'
If you want to download gradle with source and docs, the default distribution url configured in gradle-wrapper.properites will not satisfy your need.It is https://services.gradle.org/distributions/gradle-2.10-bin.zip, not https://services.gradle.org/distributions/gradle-2.10-all.zip.This full url is suggested by IDE such as Android Studio.If you want to download the full gradle,You can configure the wrapper task like this:
task wrapper(type: Wrapper) {
gradleVersion = '2.13'
distributionUrl = distributionUrl.replace("bin", "all")
}
The question is quite old so I feel like I need to give a more up to date response to this question.
Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is http://xamarin.com/
the crxml parser is a real easy to parser.
This class has got a search function, which takes a node name with any namespace as an argument. It searches the xml for the node and prints out the access statement to access that node using this class. This class also makes xml generation very easy.
you can download this class at
http://freshmeat.net/projects/crxml
or from phpclasses.org
http://www.phpclasses.org/package/6769-PHP-Manipulate-XML-documents-as-array.html
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
The below command is enough to get the path of the file from a dialog box -
my_FileName = Application.GetOpenFilename("Excel Files (*.tsv), *.txt")
You can kill a detached session which is not responding within the screen session by doing the following.
Type screen -list
to identify the detached screen session.
~$ screen -list There are screens on: 20751.Melvin_Peter_V42 (Detached)
Note: 20751.Melvin_Peter_V42
is your session id.
Get attached to the detached screen session
screen -r 20751.Melvin_Peter_V42
Once connected to the session press Ctrl + A then type :quit
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
I'd also suggest moving the event handler outside render.
var OnSubmitTest = React.createClass({
submit: function(e){
e.preventDefault();
alert('it works!');
}
render: function() {
return (
<form onSubmit={this.submit}>
<button>Click me</button>
</form>
);
}
});
Here is a method I use to both iterate an enum
and provide multiple values types from one enum
enum IterateEnum: Int {
case Zero
case One
case Two
case Three
case Four
case Five
case Six
case Seven
//tuple allows multiple values to be derived from the enum case, and
//since it is using a switch with no default, if a new case is added,
//a compiler error will be returned if it doesn't have a value tuple set
var value: (french: String, spanish: String, japanese: String) {
switch self {
case .Zero: return (french: "zéro", spanish: "cero", japanese: "nuru")
case .One: return (french: "un", spanish: "uno", japanese: "ichi")
case .Two: return (french: "deux", spanish: "dos", japanese: "ni")
case .Three: return (french: "trois", spanish: "tres", japanese: "san")
case .Four: return (french: "quatre", spanish: "cuatro", japanese: "shi")
case .Five: return (french: "cinq", spanish: "cinco", japanese: "go")
case .Six: return (french: "six", spanish: "seis", japanese: "roku")
case .Seven: return (french: "sept", spanish: "siete", japanese: "shichi")
}
}
//Used to iterate enum or otherwise access enum case by index order.
//Iterate by looping until it returns nil
static func item(index: Int) -> IterateEnum? {
return IterateEnum.init(rawValue: index)
}
static func numberFromSpanish(number: String) -> IterateEnum? {
return findItem { $0.value.spanish == number }
}
//use block to test value property to retrieve the enum case
static func findItem(predicate: ((_: IterateEnum) -> Bool)) -> IterateEnum? {
var enumIndex: Int = -1
var enumCase: IterateEnum?
//Iterate until item returns nil
repeat {
enumIndex += 1
enumCase = IterateEnum.item(index: enumIndex)
if let eCase = enumCase {
if predicate(eCase) {
return eCase
}
}
} while enumCase != nil
return nil
}
}
var enumIndex: Int = -1
var enumCase: IterateEnum?
// Iterate until item returns nil
repeat {
enumIndex += 1
enumCase = IterateEnum.item(index: enumIndex)
if let eCase = enumCase {
print("The number \(eCase) in french: \(eCase.value.french), spanish: \(eCase.value.spanish), japanese: \(eCase.value.japanese)")
}
} while enumCase != nil
print("Total of \(enumIndex) cases")
let number = IterateEnum.numberFromSpanish(number: "siete")
print("siete in japanese: \((number?.value.japanese ?? "Unknown"))")
This is the output:
The number Zero in french: zéro, spanish: cero, japanese: nuru
The number One in french: un, spanish: uno, japanese: ichi
The number Two in french: deux, spanish: dos, japanese: ni
The number Three in french: trois, spanish: tres, japanese: san
The number Four in french: quatre, spanish: cuatro, japanese: shi
The number Five in french: cinq, spanish: cinco, japanese: go
The number Six in french: six, spanish: seis, japanese: roku
The number Seven in french: sept, spanish: siete, japanese: shichi
Total of 8 cases
siete in japanese: shichi
UPDATE
I recently created a protocol to handle the enumeration. The protocol requires an enum with an Int raw value:
protocol EnumIteration {
//Used to iterate enum or otherwise access enum case by index order. Iterate by looping until it returns nil
static func item(index:Int) -> Self?
static func iterate(item:((index:Int, enumCase:Self)->()), completion:(()->())?) {
static func findItem(predicate:((enumCase:Self)->Bool)) -> Self?
static func count() -> Int
}
extension EnumIteration where Self: RawRepresentable, Self.RawValue == Int {
//Used to iterate enum or otherwise access enum case by index order. Iterate by looping until it returns nil
static func item(index:Int) -> Self? {
return Self.init(rawValue: index)
}
static func iterate(item:((index:Int, enumCase:Self)->()), completion:(()->())?) {
var enumIndex:Int = -1
var enumCase:Self?
//Iterate until item returns nil
repeat {
enumIndex += 1
enumCase = Self.item(enumIndex)
if let eCase = enumCase {
item(index: enumIndex, enumCase: eCase)
}
} while enumCase != nil
completion?()
}
static func findItem(predicate:((enumCase:Self)->Bool)) -> Self? {
var enumIndex:Int = -1
var enumCase:Self?
//Iterate until item returns nil
repeat {
enumIndex += 1
enumCase = Self.item(enumIndex)
if let eCase = enumCase {
if predicate(enumCase:eCase) {
return eCase
}
}
} while enumCase != nil
return nil
}
static func count() -> Int {
var enumIndex:Int = -1
var enumCase:Self?
//Iterate until item returns nil
repeat {
enumIndex += 1
enumCase = Self.item(enumIndex)
} while enumCase != nil
//last enumIndex (when enumCase == nil) is equal to the enum count
return enumIndex
}
}
you can check it by window
property
if(viewController.view.window){
// view visible
}else{
// no visible
}
Javascript:
window.sumInputs = function() {
var inputs = document.getElementsByTagName('input'),
result = document.getElementById('total'),
sum = 0;
for(var i=0; i<inputs.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}
}
result.value = sum;
}?
Html:
Qty1 : <input type="text" name="qty1" id="qty"/><br>
Qty2 : <input type="text" name="qty2" id="qty"/><br>
Qty3 : <input type="text" name="qty3" id="qty"/><br>
Qty4 : <input type="text" name="qty4" id="qty"/><br>
Qty5 : <input type="text" name="qty5" id="qty"/><br>
Qty6 : <input type="text" name="qty6" id="qty"/><br
Qty7 : <input type="text" name="qty7" id="qty"/><br>
Qty8 : <input type="text" name="qty8" id="qty"/><br>
<br><br>
Total : <input type="text" name="total" id="total"/>
<a href="javascript:sumInputs()">Sum</a>
Example: http://jsfiddle.net/fRd9N/1/
?
I encountered a similar problem but a complex one and since this is the first thread i found regarding that issue i decided to post my finding. i know it is complex solution to a simple problem but i hope that i could help other people who go to this thread looking for a more complex solution. i had to split a string containing 5 numbers (column name: levelsFeed) and to show each number in a separate column. for example: 8,1,2,2,2 should be shown as :
1 2 3 4 5
-------------
8 1 2 2 2
Solution 1: using XML functions: this solution for the slowest solution by far
SELECT Distinct FeedbackID,
, S.a.value('(/H/r)[1]', 'INT') AS level1
, S.a.value('(/H/r)[2]', 'INT') AS level2
, S.a.value('(/H/r)[3]', 'INT') AS level3
, S.a.value('(/H/r)[4]', 'INT') AS level4
, S.a.value('(/H/r)[5]', 'INT') AS level5
FROM (
SELECT *,CAST (N'<H><r>' + REPLACE(levelsFeed, ',', '</r><r>') + '</r> </H>' AS XML) AS [vals]
FROM Feedbacks
) as d
CROSS APPLY d.[vals].nodes('/H/r') S(a)
Solution 2: using Split function and pivot. (the split function split a string to rows with the column name Data)
SELECT FeedbackID, [1],[2],[3],[4],[5]
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY feedbackID ORDER BY (SELECT null)) as rn
FROM (
SELECT FeedbackID, levelsFeed
FROM Feedbacks
) as a
CROSS APPLY dbo.Split(levelsFeed, ',')
) as SourceTable
PIVOT
(
MAX(data)
FOR rn IN ([1],[2],[3],[4],[5])
)as pivotTable
Solution 3: using string manipulations functions - fastest by small margin over solution 2
SELECT FeedbackID,
SUBSTRING(levelsFeed,0,CHARINDEX(',',levelsFeed)) AS level1,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),4) AS level2,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),3) AS level3,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),2) AS level4,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),1) AS level5
FROM Feedbacks
since the levelsFeed contains 5 string values i needed to use the substring function for the first string.
i hope that my solution will help other that got to this thread looking for a more complex split to columns methods
new AsyncRoute({path: '/demo/:demoKey1/:demoKey2', loader: () => {
return System.import('app/modules/demo/demo').then(m =>m.demoComponent);
}, name: 'demoPage'}),
export class demoComponent {
onClick(){
this._router.navigate( ['/demoPage', {demoKey1: "123", demoKey2: "234"}]);
}
}
It's actually quite simple. Go to the font on Google's website, and add its link to the head of every page you want to include the font.
If each user has its own SQL Server login you could try this
select
so.name, su.name, so.crdate
from
sysobjects so
join
sysusers su on so.uid = su.uid
order by
so.crdate
Check for the existence by retrieving its object_id:
if object_id('tempdb..##clients_keyword') is not null
drop table ##clients_keyword
This error is caused by PDO
not being available to PHP.
If you are getting the error on the command line, or not via the same interface your website uses for PHP, you are potentially invoking a different version of PHP, or utlising a different php.ini
configuration file when checking phpinfo()
.
Ensure PDO is loaded, and the PDO drivers for your database are also loaded.
Applying
<item name="android:statusBarColor">@color/color_primary_dark</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
in Theme.AppCompat.Light.DarkActionBar
didn't worked for me. What did the trick is , giving colorPrimaryDark
as usual along with android:colorPrimary
in styles.xml
<item name="android:colorAccent">@color/color_primary</item>
<item name="android:colorPrimary">@color/color_primary</item>
<item name="android:colorPrimaryDark">@color/color_primary_dark</item>
and in setting
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
Window window = this.Window;
Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
}
didn't had to set statusbar color in code .
This should help:
import csv
import requests
CSV_URL = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'
with requests.Session() as s:
download = s.get(CSV_URL)
decoded_content = download.content.decode('utf-8')
cr = csv.reader(decoded_content.splitlines(), delimiter=',')
my_list = list(cr)
for row in my_list:
print(row)
Ouput sample:
['street', 'city', 'zip', 'state', 'beds', 'baths', 'sq__ft', 'type', 'sale_date', 'price', 'latitude', 'longitude']
['3526 HIGH ST', 'SACRAMENTO', '95838', 'CA', '2', '1', '836', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '59222', '38.631913', '-121.434879']
['51 OMAHA CT', 'SACRAMENTO', '95823', 'CA', '3', '1', '1167', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '68212', '38.478902', '-121.431028']
['2796 BRANCH ST', 'SACRAMENTO', '95815', 'CA', '2', '1', '796', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '68880', '38.618305', '-121.443839']
['2805 JANETTE WAY', 'SACRAMENTO', '95815', 'CA', '2', '1', '852', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '69307', '38.616835', '-121.439146']
[...]
Related question with answer: https://stackoverflow.com/a/33079644/295246
Edit: Other answers are useful if you need to download large files (i.e. stream=True
).
TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.
If you are calling a Python service, the code will look like below:
this.updateTalentSupplier=function(supplierObj){
var promise = $http({
method: 'POST',
url: bbConfig.BWS+'updateTalentSupplier/',
data:supplierObj,
withCredentials: false,
contentType:'application/json',
dataType:'json'
});
return promise; //Promise is returned
}
We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.
No need for a function:
$assetPath : "/assets/images";
...
body {
margin: 0 auto;
background: url(#{$assetPath}/site/background.jpg) repeat-x fixed 0 0;
width: 100%; }
See the interpolation docs for details.
How about this:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
AND TABLE_NAME = 'Your Table name'
AND COLUMN_KEY = 'PRI';
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
AND TABLE_NAME = 'Your Table name'
AND COLUMN_KEY = 'UNI';
Use background-size
property to achieve that. You should choose between cover
, contain
and 100%
- depending on what exactly you'd like to get.
import math
import turtle
ws = turtle.Screen()
ws.bgcolor("lightblue")
fred = turtle.Turtle()
for angle in range(360):
y = math.sin(math.radians(angle))
fred.goto(angle, y * 80)
ws.exitonclick()
Check out
bucket.get_key(
key_name,
headers=None,
version_id=None,
response_headers=None,
validate=True
)
Check to see if a particular key exists within the bucket. This method uses a HEAD request to check for the existence of the key. Returns: An instance of a Key object or None
from Boto S3 Docs
You can just call bucket.get_key(keyname) and check if the returned object is None.
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
In Swift, you can simply print a boolean value and it will be displayed as true
or false
.
let flag = true
print(flag) //true
Assuming type TreeMap<String,Integer> :
for(Map.Entry<String,Integer> entry : treeMap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " => " + value);
}
(key and Value types can be any class of course)
select {
outline: 0;
overflow: hidden;
height: 30px;
background: #2c343c;
color: #747a80;
border: #2c343c;
padding: 5px 3px 5px 10px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 10px;
}
select option {border: 1px solid #000; background: #010;}
What happens if the fragment that you want to remove is not on top of the stack?
Then you can use theses functions
Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf
and postgres.conf
files I finally found out that my firewall was overriding everything and therefore blocking connections
Your command should include the url parameter as stated in the script usage comments. The main function has 2 parameters, url and out (which is set to a default value) C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"
You have to be careful using the destructor. This will get called on the GC Finalizer thread. In some cases the resources that your freeing may not like being released on a different thread from the one they were created on.
The ...
(spread operator) is used in react to:
provide a neat way to pass props from parent to child components. e.g given these props in a parent component,
this.props = {
username: "danM",
email: "[email protected]"
}
they could be passed in the following manner to the child,
<ChildComponent {...this.props} />
which is similar to this
<ChildComponent username={this.props.username} email={this.props.email} />
but way cleaner.
I resolved the problem by following these steps:
Select the project - Right click - java build path.
In source tab - you change the src
to src/main/java
.
Eclipse will reorder all the project.
For legend labels can use something like below. Legendlabels are the plot lines saved. modFreq are where the name of the actual labels corresponding to the plot lines. Then the third parameter is the location of the legend. Lastly, you can pass in any arguments as I've down here but mainly need the first three. Also, you are supposed to if you set the labels correctly in the plot command. To just call legend with the location parameter and it finds the labels in each of the lines. I have had better luck making my own legend as below. Seems to work in all cases where have never seemed to get the other way going properly. If you don't understand let me know:
legendLabels = []
for i in range(modSize):
legendLabels.append(ax.plot(x,hstack((array([0]),actSum[j,semi,i,semi])), color=plotColor[i%8], dashes=dashes[i%4])[0]) #linestyle=dashs[i%4]
legArgs = dict(title='AM Templates (Hz)',bbox_to_anchor=[.4,1.05],borderpad=0.1,labelspacing=0,handlelength=1.8,handletextpad=0.05,frameon=False,ncol=4, columnspacing=0.02) #ncol,numpoints,columnspacing,title,bbox_transform,prop
leg = ax.legend(tuple(legendLabels),tuple(modFreq),'upper center',**legArgs)
leg.get_title().set_fontsize(tick_size)
You can also use the leg to change fontsizes or nearly any parameter of the legend.
Global title as stated in the above comment can be done with adding text per the link provided: http://matplotlib.sourceforge.net/examples/pylab_examples/newscalarformatter_demo.html
f.text(0.5,0.975,'The new formatter, default settings',horizontalalignment='center',
verticalalignment='top')
System.Int32.MaxValue
Assuming you mean System.Array
, ie. any normally defined array (int[]
, etc). This is the maximum number of values the array can hold. The size of each value is only limited by the amount of memory or virtual memory available to hold them.
This limit is enforced because System.Array
uses an Int32
as it's indexer, hence only valid values for an Int32
can be used. On top of this, only positive values (ie, >= 0
) may be used. This means the absolute maximum upper bound on the size of an array is the absolute maximum upper bound on values for an Int32
, which is available in Int32.MaxValue
and is equivalent to 2^31, or roughly 2 billion.
On a completely different note, if you're worrying about this, it's likely you're using alot of data, either correctly or incorrectly. In this case, I'd look into using a List<T>
instead of an array, so that you are only using as much memory as needed. Infact, I'd recommend using a List<T>
or another of the generic collection types all the time. This means that only as much memory as you are actually using will be allocated, but you can use it like you would a normal array.
The other collection of note is Dictionary<int, T>
which you can use like a normal array too, but will only be populated sparsely. For instance, in the following code, only one element will be created, instead of the 1000 that an array would create:
Dictionary<int, string> foo = new Dictionary<int, string>();
foo[1000] = "Hello world!";
Console.WriteLine(foo[1000]);
Using Dictionary
also lets you control the type of the indexer, and allows you to use negative values. For the absolute maximal sized sparse array you could use a Dictionary<ulong, T>
, which will provide more potential elements than you could possible think about.
The Home button is a very dangerous button to override and, because of that, Android will not let you override its behavior the same way you do the BACK button.
Take a look at this discussion.
You will notice that the home button seems to be implemented as a intent invocation, so you'll end up having to add an intent category to your activity. Then, any time the user hits home, your app will show up as an option. You should consider what it is you are looking to accomplish with the home button. If its not to replace the default home screen of the device, I would be wary of overloading the HOME button, but it is possible (per discussion in above thread.)
Nothing seemed to work for me until I realized that my method was declared as public final
instead of just public
. The error was being caused by the final
keyword. Removing it made the error go away.
This works because Integer::min
resolves to an implementation of the Comparator<Integer>
interface.
The method reference of Integer::min
resolves to Integer.min(int a, int b)
, resolved to IntBinaryOperator
, and presumably autoboxing occurs somewhere making it a BinaryOperator<Integer>
.
And the min()
resp max()
methods of the Stream<Integer>
ask the Comparator<Integer>
interface to be implemented.
Now this resolves to the single method Integer compareTo(Integer o1, Integer o2)
. Which is of type BinaryOperator<Integer>
.
And thus the magic has happened as both methods are a BinaryOperator<Integer>
.
Why not Process.Start(@"c:\test");
?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries
for (var [key, item] of someArray.entries()) { ... }
In TS this requires targeting ES2015 since it requires the runtime to support iterators, which ES5 runtimes don't. You can of course use something like Babel to make the output work on ES5 runtimes.