In android Oreo (API 26) you can not change orientation for Activity that have below line(s) in style
<item name="android:windowIsTranslucent">true</item>
or
<item name="android:windowIsFloating">true</item>
You have several way to solving this :
1) You can simply remove above line(s) (or turn it to false) and your app works fine.
2) Or you can first remove below line from manifest for that activity
android:screenOrientation="portrait"
Then you must add this line to your activity (in onCreate())
//android O fix bug orientation
if (android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
3) You can create new styles.xml
in values-v26
folder and add this to your style.xml
. (Thanks to AbdelHady comment)
<item name="android:windowIsTranslucent">false</item>
<item name="android:windowIsFloating">false</item>
protected void onCreate(Bundle savedInstanceState) { /* * Your OnCreate */ Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType();
//VIEW"
if (Intent.ACTION_VIEW.equals(action) && type != null) {viewhekper(intent);//Handle text being sent}
Change ng-disabled="!contractTypeValid"
to [disabled]="!contractTypeValid"
I was facing the same problem. Issue was that I was importing some class from index.ts
import {className} from '..shared/index'
index.ts contain the export statement
export * from './models';
I changed it to the .ts file which contain the actual class object
import {className} from '..shared/model'
and it resolved.
Flow allows interface specification, without having to convert your whole code base to TypeScript.
Interfaces are a way of breaking dependencies, while stepping cautiously within existing code.
It happen that after some time we need to run
'php artisan passport:install --force
again to generate a key this solved my problem ,
client = new OkHttpClient();
Request request = new Request.Builder().header("authorization", token).url(url).build();
MyWebSocketListener wsListener = new MyWebSocketListener(LudoRoomActivity.this);
client.newWebSocket(request, wsListener);
client.dispatcher().executorService().shutdown();
I added TO_DATE
and it resolved issue.
Before modification - due to below condition i got this error
record_update_dt>='05-May-2017'
After modification - after adding to_date
, issue got resolved.
record_update_dt>=to_date('05-May-2017','DD-Mon-YYYY')
If you're using 0
and an empty string ''
and null
to designate undefined you've got a data problem. Just update the columns and fix your schema.
UPDATE pt.incentive_channel
SET pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';
This will make joining and selecting substantially easier moving forward.
Why don't you use spring's TransactionTemplate
to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional
method, but given that it's a test I would opt for programmatic control of your transactions.
Also note that the @Transactional
annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!
@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {
@Autowired
PlatformTransactionManager platformTransactionManager;
TransactionTemplate transactionTemplate;
@Before
public void setUp() throws Exception {
transactionTemplate = new TransactionTemplate(platformTransactionManager);
}
@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {
final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
@Override
public Contract doInTransaction(TransactionStatus status) {
Contract c = contractDOD.getNewTransientContract(15);
contractRepository.save(c);
return c;
}
});
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; ++i) {
executorService.execute(new Runnable() {
@Override //note that there is no @Transactional configured for the method
public void run() {
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// do whatever you want to do with c1
return null;
}
});
}
});
}
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// validate test results in transaction
return null;
}
});
}
}
JObject implements IDictionary, so you can use it that way. For ex,
var cycleJson = JObject.Parse(@"{""name"":""john""}");
//add surname
cycleJson["surname"] = "doe";
//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
So the final json will be
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
You can also use dynamic
keyword
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });
Try this, just an example:
u.UserTypeOptions = new SelectList(new[]
{
new { ID="1", Name="name1" },
new { ID="2", Name="name2" },
new { ID="3", Name="name3" },
}, "ID", "Name", 1);
Or
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
},"Value","Text");
Open IIS And right click on Default App Pool and Add Binding to make application work with HTTPS protocol.
type : https
IP address : All unassigned
port no : 443
SSL Certificate : WMSVC
then
Click on and restart IIS
Done
Here is a more easier way of doing this if you are using Laravel PHP framework :
<?php
// usage anywhere
// returns HelloWorld
$name = class_basename('Path\To\YourClass\HelloWorld');
// usage inside a class
// returns HelloWorld
$name = class_basename(__CLASS__);
try this, worked for me ! . Just use intent
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(whatsappUrl()));
startActivity(intent);
Build whatsapp url. add country code in whatsapp phone number https://countrycode.org/
public static String whatsappUrl(){
final String BASE_URL = "https://api.whatsapp.com/";
final String WHATSAPP_PHONE_NUMBER = "628123232323"; //'62' is country code for Indonesia
final String PARAM_PHONE_NUMBER = "phone";
final String PARAM_TEXT = "text";
final String TEXT_VALUE = "Hello, How are you ?";
String newUrl = BASE_URL + "send";
Uri builtUri = Uri.parse(newUrl).buildUpon()
.appendQueryParameter(PARAM_PHONE_NUMBER, WHATSAPP_PHONE_NUMBER)
.appendQueryParameter(PARAM_TEXT, TEXT_VALUE)
.build();
return buildUrl(builtUri).toString();
}
public static URL buildUrl(Uri myUri){
URL finalUrl = null;
try {
finalUrl = new URL(myUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return finalUrl;
}
You can use the mktime(hour, minute, seconds, month, day, year) function
$paymentDate = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
$contractDateBegin = mktime(0, 0, 0, 1, 1, 2001);
$contractDateEnd = mktime(0, 0, 0, 1, 1, 2012);
if ($paymentDate >= $contractDateBegin && $paymentDate <= $contractDateEnd){
echo "is between";
}else{
echo "NO GO!";
}
In our case, beside changing ToolsVersion from 14.0 to 15.0 on .csproj projet file, as stated by Dominik Litschauer, we also had to install an updated version of MSBuild, since compilation is being triggered by a Jenkins job. After installing Build Tools for Visual Studio 2019, we had got MsBuild version 16.0 and all new C# features compiled ok.
Use the following code to get the response object from the AFHTTPSessionManager
failure block; then you can convert the generic type into the required data type:
id responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
Hi this happens when the front end and backend is running on different ports. The browser blocks the responses from the backend due to the absence on CORS headers. The solution is to make add the CORS headers in the backend request. The easiest way is to use cors npm package.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
This will enable CORS headers in all your request. For more information you can refer to cors documentation
Removing ComponentModelCache
did not work for me. Reinstalling VS 2019 did thanks to a recommendation on this Microsoft support thread.
Details
Right click on the .svc file in Solution Explorer and click View Markup
<%@ ServiceHost Language="C#" Debug="true"
Service="MyService.**GetHistoryInfo**"
CodeBehind="GetHistoryInfo.svc.cs" %>
Update the service reference where you are referring to.
Different case but may help someone,
In my case Window firewall was enabled on Server,
Two thinks can be done,
1) Disable windows firewall (your on risk but it will get thing work)
2) Add port in inbound rule.
Thanks .
The contract is that if obj1.equals(obj2)
then obj1.hashCode() == obj2.hashCode()
, it is mainly for performance reasons, as maps are mainly using hashCode method to compare entries keys.
you may simply create your string in multiple steps, a bit redundant but it keeps the code readable and maintain sanity while debugging or editing
SqlQueryString = "Insert into Employee values("
SqlQueryString = SqlQueryString & txtEmployeeNo.Value & " ,"
SqlQueryString = SqlQueryString & " '" & txtEmployeeNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtFloor.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtLeaves.Value & "' )"
Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
});
I run into naming problem. Service name has to be exactly name of your implementation. If mismatched, it uses by default basicHttpBinding
resulting in text/xml
content type.
Name of your class is on two places - SVC markup and CS file.
Check endpoint contract too - again exact name of your interface, nothing more. I've added assembly name which just can't be there.
<service name="MyNamespace.MyService">
<endpoint address="" binding="wsHttpBinding" contract="MyNamespace.IMyService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
When I ran into this error, I spent hours trying to find a solution.
My issue was that when I went to save the file I had accidentally hit the key stroke "G" in the web.config. I had a straggler Character just sittings outside, so the web.config did not know how to interpret the improperly formatted data.
Hope this helps.
You can use standard JS toFixed
method
var num = 5.56789;
var n=num.toFixed(2);
//5.57
In order to add commas (to separate 1000's) you can add regexp as follows (where num
is a number):
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000
Complete example:
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//document.write(num) would write value as follows: $1,250.22
Separation character depends on country and locale. For some countries it may need to be .
If attribute routing is being used, you can use the [FromUri] and [FromBody] attributes.
Example:
[HttpPost()]
[Route("api/products/{id:int}")]
public HttpResponseMessage AddProduct([FromUri()] int id, [FromBody()] Product product)
{
// Add product
}
Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.
Check this : Using Large Message Requests in Silverlight with WCF
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="TestLargeWCF.Web.MyServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="customBinding0">
<binaryMessageEncoding />
<!-- Start change -->
<httpTransport maxReceivedMessageSize="2097152"
maxBufferSize="2097152"
maxBufferPoolSize="2097152"/>
<!-- Stop change -->
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
<endpoint address=""
binding="customBinding"
bindingConfiguration="customBinding0"
contract="TestLargeWCF.Web.MyService"/>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
You need to set the NTAuthenticationProviders to NTLM
MSDN Article: https://msdn.microsoft.com/en-us/library/ee248703(VS.90).aspx
IIS Command-line (http://msdn.microsoft.com/en-us/library/ms525006(v=vs.90).aspx):
cscript adsutil.vbs set w3svc/WebSiteValueData/root/NTAuthenticationProviders "NTLM"
Note : This answer is now out-of-date. You are now required to have an API key to use google maps. Read More
you need to change your API from V2 to V3, Since Google Map Version 3 don't required API Key
Check this out..
write your script
as
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
Why not simply use List#equals
?
assertEquals(argumentComponents, imapPathComponents);
two lists are defined to be equal if they contain the same elements in the same order.
public async Task<model> GetSomething(int id)
{
return await context.model.FindAsync(id);
}
This is the better solution:
verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));
Consider the following case:
First, o1.compareTo(o2)
is called. card1.getSet() == card2.getSet()
happens to be true and so is card1.getRarity() < card2.getRarity()
, so you return 1.
Then, o2.compareTo(o1)
is called. Again, card1.getSet() == card2.getSet()
is true. Then, you skip to the following else
, then card1.getId() == card2.getId()
happens to be true, and so is cardType > item.getCardType()
. You return 1 again.
From that, o1 > o2
, and o2 > o1
. You broke the contract.
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
Before changing stored procedure please check what is the output of your current one. In SQL Server Management run following:
DECLARE @NewId int
EXEC @return_value = [dbo].[usp_InsertContract]
N'Gary',
@NewId OUTPUT
SELECT @NewId
See what it returns. This may give you some hints of why your out param is not filled.
Most of answers works beside a fact, that when u scroll to the bottom, listener is triggered several times, which in my case is undesirable. To avoid this behavior I've added flag scrollPositionChanged that checks if scroll position even changed before calling method once again.
public class EndDetectingScrollView extends ScrollView {
private boolean scrollPositionChanged = true;
private ScrollEndingListener scrollEndingListener;
public interface ScrollEndingListener {
void onScrolledToEnd();
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
View view = this.getChildAt(this.getChildCount() - 1);
int diff = (view.getBottom() - (this.getHeight() + this.getScrollY()));
if (diff <= 0) {
if (scrollPositionChanged) {
scrollPositionChanged = false;
if (scrollEndingListener != null) {
scrollEndingListener.onScrolledToEnd();
}
}
} else {
scrollPositionChanged = true;
}
}
public void setScrollEndingListener(ScrollEndingListener scrollEndingListener) {
this.scrollEndingListener = scrollEndingListener;
}
}
Then just set listener
scrollView.setScrollEndingListener(new EndDetectingScrollView.ScrollEndingListener() {
@Override
public void onScrolledToEnd() {
//do your stuff here
}
});
You may do the same thing if u do in like
scrollView.getViewTreeObserver().addOnScrollChangedListener(...)
but you have to provide flag from class your adding this listener.
I believe that the best format for universal interoperability is not the ISO-8601 string, but rather the format used by EJSON:
{ "myDateField": { "$date" : <ms-since-epoch> } }
As described here: https://docs.meteor.com/api/ejson.html
Benefits
Conclusion
I understand that a human-readable format (ISO-8601 string) is helpful and more convenient for 80% of use cases, and indeed no-one should ever be told not to store their dates as ISO-8601 strings if that's what their applications understand, but for a universally accepted transport format which should guarantee certain values to for sure be dates, how can we allow for ambiguity and need for so much validation?
Simple Answer: NO. You cannot help ad hoc queries on a 238 column table with a 50% Fill Factor on the Clustered Index.
Detailed Answer:
As I have stated in other answers on this topic, Index design is both Art and Science and there are so many factors to consider that there are few, if any, hard and fast rules. You need to consider: the volume of DML operations vs SELECTs, disk subsystem, other indexes / triggers on the table, distribution of data within the table, are queries using SARGable WHERE conditions, and several other things that I can't even remember right now.
I can say that no help can be given for questions on this topic without an understanding of the Table itself, its indexes, triggers, etc. Now that you have posted the table definition (still waiting on the Indexes but the Table definition alone points to 99% of the issue) I can offer some suggestions.
First, if the table definition is accurate (238 columns, 50% Fill Factor) then you can pretty much ignore the rest of the answers / advice here ;-). Sorry to be less-than-political here, but seriously, it's a wild goose chase without knowing the specifics. And now that we see the table definition it becomes quite a bit clearer as to why a simple query would take so long, even when the test queries (Update #1) ran so quickly.
The main problem here (and in many poor-performance situations) is bad data modeling. 238 columns is not prohibited just like having 999 indexes is not prohibited, but it is also generally not very wise.
Recommendations:
ANSI_PADDING OFF
is disturbing, not to mention inconsistent within the table due to the various column additions over time. Not sure if you can fix that now, but ideally you would always have ANSI_PADDING ON
, or at the very least have the same setting across all ALTER TABLE
statements.PRIMARY
as that is where SQL SERVER stores all of its data and meta-data about your objects. You create your Table and Clustered Index (as that is the data for the table) on [Tables]
and all Non-Clustered indexes on [Indexes]
WHERE
condition, then consider moving that to the leading column of the clustered index. Assuming that it is used more often than "ER101_ORD_NBR". If "ER101_ORD_NBR" is used more often then keep it. It just seems, assuming that the field names mean "OrganizationCode" and "OrderNumber", that "OrgCode" is a better grouping that might have multiple "OrderNumbers" within it.CHAR(2)
instead of VARCHAR(2)
as it will save a byte in the row header which tracks variable width sizes and adds up over millions of rows.SELECT *
will hurt performance. Not only due to it requiring SQL Server to return all columns and hence be more likely to do a Clustered Index Scan regardless of your other indexes, but it also takes SQL Server time to go to the table definition and translate *
into all of the column names. It should be slightly faster to specify all 238 column names in the SELECT
list though that won't help the Scan issue. But do you ever really need all 238 columns at the same time anyway?Good luck!
UPDATE
For the sake of completeness to the question "how to improve performance on a large table for ad-hoc queries", it should be noted that while it will not help for this specific case, IF someone is using SQL Server 2012 (or newer when that time comes) and IF the table is not being updated, then using Columnstore Indexes is an option. For more details on that new feature, look here:
http://msdn.microsoft.com/en-us/library/gg492088.aspx (I believe these were made to be updateable starting in SQL Server 2014).
UPDATE 2
Additional considerations are:
INT
, BIGINT
, TINYINT
, SMALLINT
, CHAR
, NCHAR
, BINARY
, DATETIME
, SMALLDATETIME
, MONEY
, etc) and well over 50% of the rows are NULL
, then consider enabling the SPARSE
option which became available in SQL Server 2008. Please see the MSDN page for Use Sparse Columns for details.I solved the issue by adding https binding in my IIS websites and adding 443 SSL port and selecting a self signed certificate in binding.
@robertc has it right, but you also need to notice that svg, #container
causes the svg to be scaled exponentially for anything but 100% (once for #container
and once for svg
).
In other words, if I applied 50% h/w to both elements, it's actually 50% of 50%, or .5 * .5, which equals .25, or 25% scale.
One selector works fine when used as @robertc suggests.
svg {
width:50%;
height:50%;
}
Close iis express and all the browsers (if the url was opened in any of the browser). Also open the visual studio IDE in admin mode. This has resolved my issue.
Editing VM Configuration worked for me.
-Djava.util.Arrays.useLegacyMergeSort=true
You must have forgotten to add a using statement to the file like this:
using System.Linq;
I arrived at this question looking for a way to stream an open ended list of objects onto a System.IO.Stream
and read them off the other end, without buffering the entire list before sending. (Specifically I'm streaming persisted objects from MongoDB over Web API.)
@Paul Tyng and @Rivers did an excellent job answering the original question, and I used their answers to build a proof of concept for my problem. I decided to post my test console app here in case anyone else is facing the same issue.
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace TestJsonStream {
class Program {
static void Main(string[] args) {
using(var writeStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.None)) {
string pipeHandle = writeStream.GetClientHandleAsString();
var writeTask = Task.Run(() => {
using(var sw = new StreamWriter(writeStream))
using(var writer = new JsonTextWriter(sw)) {
var ser = new JsonSerializer();
writer.WriteStartArray();
for(int i = 0; i < 25; i++) {
ser.Serialize(writer, new DataItem { Item = i });
writer.Flush();
Thread.Sleep(500);
}
writer.WriteEnd();
writer.Flush();
}
});
var readTask = Task.Run(() => {
var sw = new Stopwatch();
sw.Start();
using(var readStream = new AnonymousPipeClientStream(pipeHandle))
using(var sr = new StreamReader(readStream))
using(var reader = new JsonTextReader(sr)) {
var ser = new JsonSerializer();
if(!reader.Read() || reader.TokenType != JsonToken.StartArray) {
throw new Exception("Expected start of array");
}
while(reader.Read()) {
if(reader.TokenType == JsonToken.EndArray) break;
var item = ser.Deserialize<DataItem>(reader);
Console.WriteLine("[{0}] Received item: {1}", sw.Elapsed, item);
}
}
});
Task.WaitAll(writeTask, readTask);
writeStream.DisposeLocalCopyOfClientHandle();
}
}
class DataItem {
public int Item { get; set; }
public override string ToString() {
return string.Format("{{ Item = {0} }}", Item);
}
}
}
}
Note that you may receive an exception when the AnonymousPipeServerStream
is disposed, I ignored this as it isn't relevant to the problem at hand.
I solved this problem by adding C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\System.Runtime.Serialization.dll in the reference
I created this simple example from different search results on the internet.
public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
//Create base address
string baseAddress = "net.pipe://localhost/MyService";
ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));
//Net named pipe
NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);
//MEX - Meta data exchange
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");
return serviceHost;
}
Using the above URI I can add a reference in my client to the web service.
What's the first part of your Subversion repository URL?
I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.
If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.
The only way around that is to log into a local machine over the VPN, and then do everything from that system.
I just make some test, it turns out that, inside nodejs's module code, it should something like this:
var module.exports = {};
var exports = module.exports;
so:
exports = function(){}; // this will not work! as it make the exports to some other pointer
module.exports = function(){}; // it works! cause finally nodejs make the module.exports to export.
exports.abc = function(){}; // works!
exports.efg = function(){}; // works!
module.exports = function(){}; // from now on we have to using module.exports to attach more stuff to exports.
module.exports.a = 'value a'; // works
exports.b = 'value b'; // the b will nerver be seen cause of the first line of code we have do it before (or later)
protected void gvTurnos_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.EmptyDataRow)
{
LinkButton btn = (LinkButton)e.Row.FindControl("btnAgregarVacio");
if (btn != null)
{
btn.Visible = rbFiltroEstatusCampus.SelectedValue == "1" ? true : false;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
try this
combobox.SelectedIndex = BindingSource.Item(9) where "9 = colum name 9 from table"
My problem was, that return type of my service was string. But I returned string of type xml:
<reponse><state>1</state><message>Operation was successfull</message</response>
so error was thrown.
public Point2D(Point2D point) : this(point.X, point.Y) { }
I had this error and it was caused by the recevier contract not implementing the method being called. Basically, someone hadn't deployed the lastest version of the WCF service to the host server.
Hy, In my case this error appeared because the Application pool of the webservice had the wrong 32/64 bit setting. So this error needed the following fix: you go to the IIS, select the site of the webservice , go to Advanced setting and get the application pool. Then go to Application pools, select it, go to "Advanced settings..." , select the "Enable 32 bit applications" and make it Enable or Disable, according to the 32/64 bit type of your webservice. If the setting is True, it means that it only allows 32 bit applications, so for 64 bit apps you have to make it "Disable" (default).
Most of the time this happens due to less memory space. first check then try some other tricks .
So your endpoint address defined in your first example is incomplete. You must also define endpoint identity as shown in client configuration. In code you can try this:
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
var address = new EndpointAddress("http://id.web/Services/EchoService.svc", spn);
var client = new EchoServiceClient(address);
litResponse.Text = client.SendEcho("Hello World");
client.Close();
Actual working final version by valamas
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri("http://id.web/Services/EchoService.svc");
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.SendEcho("Hello World");
client.Close();
This best for XML Deserialize
public static object Deserialize(string xml, Type toType)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
return xSerializer.Deserialize(str);
}
}
With latest version of windows (e.g. Windows 10, other servers), type/search for "Developers Command prompt.." It will pop up the relevant command prompt for the Visual Studio version.
e.g. Developer Command Prompt for VS 2015
More here https://msdn.microsoft.com/en-us/library/ms229859(v=vs.110).aspx
use property UseSimpleDictionaryFormat
on DataContractJsonSerializer
and set it to true
.
Does the job :)
Also when you call from http request it will work properly but when your try to call from net.tcp that time you get all this kind stuff
There are several good articles on the subject on dev2qa.com site, about Contacts Provider
API:
How To Add Contact In Android Programmatically
How To Update Delete Android Contacts Programmatically
How To Get Contact List In Android Programmatically
Contacts are stored in SQLite .db files in bunch of tables, the structure is discussed here: Android Contacts Database Structure
Official Google documentation on Contacts Provider here
I have a similar problem with references not being recognized in VS2010 and the answers herein were not able to correct it.
The problem in my solution was related to the extension of the path where the project referenced was located. As I am working with SVN, I made a branch of a repository to do some testing and that branch increased two levels in path structure, so the path became too long to be usable in windows. This did not throw any error but did not recognize the namespace of the project reference. When I correct the location of the project to have a smaller path everything went fine.
I solved using a "manual" deserialization. I'll explain in code
public ActionResult MyMethod([System.Web.Http.FromBody] MyModel model)
{
if (module.Fields == null && !string.IsNullOrEmpty(Request.Form["fields"]))
{
model.Fields = JsonConvert.DeserializeObject<MyFieldModel[]>(Request.Form["fields"]);
}
//... more code
}
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
Since the currently proposed implementations which do implement a sorted list by breaking the Collection API, have an own implementation of a tree or something similar, I was curios how an implementation based on the TreeMap would perform. (Especialy since the TreeSet does base on TreeMap, too)
If someone is interested in that, too, he or she can feel free to look into it:
Its part of the core library, you can add it via Maven dependency of course. (Apache License)
Currently the implementation seems to compare quite well on the same level than the guava SortedMultiSet and to the TreeList of the Apache Commons library.
But I would be happy if more than only me would test the implementation to be sure I did not miss something important.
Best regards!
Restarting Visual Studio did the trick for me. I am using VS 2015.
Put ALTER COLUMN
statement inside a bracket, it should work.
ALTER TABLE tblcommodityOHLC alter ( column
CC_CommodityContractID NUMERIC(18,0),
CM_CommodityID NUMERIC(18,0) )
.NET 4.0 has a built-in library to do this:
using System.Web.Script.Serialization;
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(str);
This is the simplest way.
Adding new items to String array.
String[] myArray = new String[] {"x", "y"};
// Convert array to list
List<String> listFromArray = Arrays.asList(myArray);
// Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
List<String> tempList = new ArrayList<String>(listFromArray);
tempList.add("z");
//Convert list back to array
String[] tempArray = new String[tempList.size()];
myArray = tempList.toArray(tempArray);
After many answers that did not work, I finally found a solution when Anonymous access is Disabled on the IIS server. Our server is using Windows authentication, not Kerberos. This is thanks to this blog posting.
No changes were made to web.config.
On the server side, the .SVC file in the ISAPI folder uses MultipleBaseAddressBasicHttpBindingServiceHostFactory
The class attributes of the service are:
[BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class InvoiceServices : IInvoiceServices
{
...
}
On the client side, the key that made it work was the http binding security attributes:
EndpointAddress endpoint =
new EndpointAddress(new Uri("http://SharePointserver/_vti_bin/InvoiceServices.svc"));
BasicHttpBinding httpBinding = new BasicHttpBinding();
httpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
InvoiceServicesClient myClient = new InvoiceServicesClient(httpBinding, endpoint);
myClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
(call service)
I hope this works for you!
I found my I had built my object incorrectly. I used http://json2csharp.com/ to generate me my object class from the JSON. Once I had the correct Oject I was able to cast without issue. Norbit, Noob mistake. Thought I'd add it in case you have the same issue.
Its a good to remember that config files can be split across secondary files to make config changes easier on different servers (dev/demo/production etc), without having to recompile code/app etc. For example we use them to allow onsite engineers to make endpoint changes without actually touching the 'real' files.
First step is to move the bindings section out of the WPF App.Config into it's own separate file.
The behaviours section is set to allow both http and https (doesn't seem to have an affect on the app if both are allowed)
<serviceMetadata httpsGetEnabled="true" httpGetEnabled="true" />
And we move the bindings section out to its own file;
<bindings configSource="Bindings.config" />
In the bindings.config file we switch the security based on protocol
<!-- None = http:// -->
<!-- Transport = https:// -->
<security mode="None" >
Now the on site engineers only need to change the Bindings.Config file and the Client.Config where we store the actual URL for each endpoint.
This way we can change the endpoint from http to https and back again to test the app without having to change any code.
Hope this helps.
This error will occur if the configuration file of the hosting application of your WCF service does not have the proper configuration.
Remember this comment from configuration:
When deploying the service library project, the content of the config file must be added to the host's app.config file. System.Configuration does not support config files for libraries.
If you have a WCF Service hosted in IIS, during runtime via VS.NET it will read the app.config of the service library project, but read the host's web.config once deployed. If web.config does not have the identical <system.serviceModel>
configuration you will receive this error. Make sure to copy over the configuration from app.config once it has been perfected.
I faced the same problem, and resolved it by changing the BodyStyle attribut value to "WebMessageBodyStyle.Bare" :
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProjectWithGeocodings/{projectId}")]
GeoCod_Project GetProjectWithGeocodings(string projectId);
The returned object will no longer be wrapped.
Since everything was working fine for weeks then stopped, I doubt this has anything to do with your code. Perhaps the error is occurring when the service is activated within IIS/ASP.NET, not when your code is called. The runtime could just be checking the configuration of the web site and throwing a generic error message which has nothing to do with the service.
My suspicion is that a certificate has expired or that the bindings are set up incorrectly. If the web site is mis-configured for HTTPS, whether your code uses them or not, you may be getting this error.
I liked the bubble sort extension method approach on "Richie"'s blog above, but I don't necessarily want to just sort comparing the entire object. I more often want to sort on a specific property of the object. So I modified it to accept a key selector the way OrderBy does so you can choose which property to sort on:
public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector)
{
if (source == null) return;
Comparer<TKey> comparer = Comparer<TKey>.Default;
for (int i = source.Count - 1; i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
TSource o1 = source[j - 1];
TSource o2 = source[j];
if (comparer.Compare(keySelector(o1), keySelector(o2)) > 0)
{
source.Remove(o1);
source.Insert(j, o1);
}
}
}
}
Which you would call the same way you would call OrderBy except it will sort the existing instance of your ObservableCollection instead of returning a new collection:
ObservableCollection<Person> people = new ObservableCollection<Person>();
...
people.Sort(p => p.FirstName);
Additionally, DataContractSerializer will serialize items marked as [Serializable] and will also serialize unmarked types in .NET 3.5 SP1 and later, to allow support for serializing anonymous types.
So, it depends on how you've decorated your class as to how to keep a member from serializing:
[DataContract]
, then remove the [DataMember]
for the property.[Serializable]
, then add [NonSerialized]
in front of the field for the property.[IgnoreDataMember]
to the property.The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html
The method DocumentBuilder.parse(String)
takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream
or Reader
, for example a StringReader
. ... Welcome to the Java standard levels of indirections !
Basically :
DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));
Note that if you read your XML from a file, you can directly give the File
object to DocumentBuilder.parse()
.
As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !
Got the same error recently but was able to fixed it by ensuring to close every wcf client call. eg.
WCFServiceClient client = new WCFServiceClient ();
//More codes here
// Always close the client.
client.Close();
or
using(WCFServiceClient client = new WCFServiceClient ())
{
//More codes here
}
Try with this:
catch (System.Reflection.TargetInvocationException e1)
String excType
excType = e1.InnerException.GetType().ToString()
choose case excType
case "System.ServiceModel.FaultException"
System.ServiceModel.FaultException e2
e2 = e1.InnerException
System.ServiceModel.Channels.MessageFault fault
fault = e2.CreateMessageFault()
ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + fault.Reason.ToString()
if (fault.HasDetail) then
System.Xml.XmlReader reader
reader = fault.GetReaderAtDetailContents()
ls_message += " " + reader.Value
do while reader.Read()
ls_message += reader.Value
loop
end if
case "System.Text.DecoderFallbackException"
System.Text.DecoderFallbackException e3
e3 = e1.InnerException
ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + e3.Message
case else
ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + e1.Message
end choose
MessageBox ( "Error", ls_message )
//logError(ls_message)
return false
This can also be achieved with jsp:include. Chad Darby explains well here in this video https://www.youtube.com/watch?v=EWbYj0qoNHo
Your data class doesn't match the JSON object. Use this instead:
[DataContract]
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
}
[DataContract]
public class ResponseData
{
[DataMember]
public IEnumerable<Results> results { get; set; }
}
[DataContract]
public class Results
{
[DataMember]
public string unescapedUrl { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string visibleUrl { get; set; }
[DataMember]
public string cacheUrl { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string titleNoFormatting { get; set; }
[DataMember]
public string content { get; set; }
}
Also, you don't have to instantiate the class to get its type for deserialization:
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
Annoyingly enough, if you want to use the default model binders, it looks like you will have to use numerical index values like a form POST.
See the following excerpt from this article http://msdn.microsoft.com/en-us/magazine/hh781022.aspx:
Though it’s somewhat counterintuitive, JSON requests have the same requirements—they, too, must adhere to the form post naming syntax. Take, for example, the JSON payload for the previous UnitPrice collection. The pure JSON array syntax for this data would be represented as:
[ { "Code": "USD", "Amount": 100.00 }, { "Code": "EUR", "Amount": 73.64 } ]
However, the default value providers and model binders require the data to be represented as a JSON form post:
{ "UnitPrice[0].Code": "USD", "UnitPrice[0].Amount": 100.00, "UnitPrice[1].Code": "EUR", "UnitPrice[1].Amount": 73.64 }
The complex object collection scenario is perhaps one of the most widely problematic scenarios that developers run into because the syntax isn’t necessarily evident to all developers. However, once you learn the relatively simple syntax for posting complex collections, these scenarios become much easier to deal with.
Actually I am preferring to use NEW_BROKER
,it is working fine on all cases:
ALTER DATABASE [dbname] SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
I see this isn't answered yet, this is an exact quote from here:
WSHttpBinding will try and perform an internal negotiate at the SSP layer. In order for this to be successful, you will need to allow anonymous in IIS for the VDir. WCF will then by default perfrom an SPNEGO for window credentials. Allowing anonymous at IIS layer is not allowing anyone in, it is deferring to the WCF stack.
I found this via: http://fczaja.blogspot.com/2009/10/http-request-is-unauthorized-with.html
After googling: http://www.google.tt/#hl=en&source=hp&q=+The+HTTP+request+is+unauthorized+with+client+authentication+scheme+%27Anonymous
this short code worked for me:
Configuration wConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup wServiceSection = ServiceModelSectionGroup.GetSectionGroup(wConfig);
ClientSection wClientSection = wServiceSection.Client;
wClientSection.Endpoints[0].Address = <your address>;
wConfig.Save();
Of course you have to create the ServiceClient proxy AFTER the config has changed. You also need to reference the System.Configuration and System.ServiceModel assemblies to make this work.
Cheers
Try changing the security mode from "Transport" to "None".
<!-- Transport security mode requires IIS to have a
certificate configured for SSL. See readme for
more information on how to set this up. -->
<security mode="None">
Are you sure your web service is deployed correctly to the enviornment that is NOT working. Looks like the type is out of date.
In my case, it was not working even after trying all solutions and setting all limits to max. In last I found out that a Microsoft IIS filtering module Url Scan 3.1 was installed on IIS/website, which have it's own limit to reject incoming requests based on content size and return "404 Not found page".
It's limit can be updated in %windir%\System32\inetsrv\urlscan\UrlScan.ini
file by setting MaxAllowedContentLength
to the required value.
For eg. following will allow upto 300 mb requests
MaxAllowedContentLength=314572800
Hope it will help someone!
Not sure if it's really a problem, but I see you have the same name for your binding configuration ().
I usually try to call my endpoints something like "UserServiceBasicHttp" or something similar (the "Binding" really doesn't have anything to do here), and I try to call my binding configurations something with "....Configuration", e.g. "UserServiceDefaultBinding", to avoid any potential name clashes.
Marc
From my recent experience i would recommend ksoap library to consume a Soap WCF Service, its actually really easy, this anddev thread migh help you out too.
Why not like this?
SELECT count(1)
FROM AD_CurrentView
WHERE myColumn=1
In .Net 4, you can use the multipleSiteBindingsEnabled
option:
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
</system.serviceModel>
Then, you won't have to specify each address.
In my case i am setting security mode to "TransportCredentialOnly" instead of "Transport" in binding. Changing it resolved the issue
<bindings>
<webHttpBinding>
<binding name="webHttpSecure">
<security mode="Transport">
<transport clientCredentialType="Windows" ></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
In case if you are using WPF application using PRISM framework then configuration should exist in your start up project (i.e. in the project where your bootstrapper resides.)
You can try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContract's, Any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.
Basic Example
var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = customer.ToJson();
var fromJson = json.FromJson<Customer>();
Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.
What you seem to want would allow for a static method to be called via both the Type or any instance of that type. This would at very least result in ambiguity which is not a desirable trait.
There would be endless debates about whether it mattered, which is best practice and whether there are performance issues doing it one way or another. By simply not supporting it C# saves us having to worry about it.
Its also likely that a compilier that conformed to this desire would lose some optimisations that may come with a more strict separation between instance and static methods.
Utilizing the "dynamic table" capability in SQL Server (querying against a parenthesis-surrounded query), you can return 2000, 49 w/ the following. If your platform doesn't offer an equivalent to the "dynamic table" ANSI-extention, you can always utilize a temp table in two-steps/statement by inserting the results within the "dynamic table" to a temp table, and then performing a subsequent select on the temp table.
DECLARE @T TABLE(
[contract] INT,
project INT,
activity INT
)
INSERT INTO @T VALUES( 1000, 8000, 10 )
INSERT INTO @T VALUES( 1000, 8000, 20 )
INSERT INTO @T VALUES( 1000, 8001, 10 )
INSERT INTO @T VALUES( 2000, 9000, 49 )
INSERT INTO @T VALUES( 2000, 9001, 49 )
INSERT INTO @T VALUES( 3000, 9000, 79 )
INSERT INTO @T VALUES( 3000, 9000, 78 )
SELECT
[contract],
[Activity] = max (activity)
FROM
(
SELECT
[contract],
[Activity]
FROM
@T
GROUP BY
[contract],
[Activity]
) t
GROUP BY
[contract]
HAVING count (*) = 1
You are making it complicated. string
is already nullable. You don't need to make it more nullable. Take out the ?
on the property type.
I ran into this exact same issue today. I had installed IIS, but did not have the activate WCF Services Enabled under .net framework 4.6.
You could use SysInternal's PsExec.
In my case i am setting security mode to "TransportCredentialOnly" instead of "Transport" in binding. Changing it resolved the issue
<bindings>
<webHttpBinding>
<binding name="webHttpSecure">
<security mode="Transport">
<transport clientCredentialType="Windows" ></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
If you just want to select the used range, use
ActiveSheet.UsedRange.Select
If you want to select from A1 to the end of the used range, you can use the SpecialCells method like this
With ActiveSheet
.Range(.Cells(1, 1), .Cells.SpecialCells(xlCellTypeLastCell)).Select
End With
Sometimes Excel gets confused on what is the last cell. It's never a smaller range than the actual used range, but it can be bigger if some cells were deleted. To avoid that, you can use Find and the asterisk wildcard to find the real last cell.
Dim rLastCell As Range
With Sheet1
Set rLastCell = .Cells.Find("*", .Cells(1, 1), xlValues, xlPart, , xlPrevious)
.Range(.Cells(1, 1), rLastCell).Select
End With
Finally, make sure you're only selecting if you really need to. Most of what you need to do in Excel VBA you can do directly to the Range rather than selecting it first. Instead of
.Range(.Cells(1, 1), rLastCell).Select
Selection.Font.Bold = True
You can
.Range(.Cells(1,1), rLastCells).Font.Bold = True
if you want to get "terse" :)
List<string>GlobalStrings = new List<string>();
for(int x=1; x<10; x++) GlobalStrings.AddRange(new List<string> { "some value", "another value"});
You can simply just pass the attribute you want without any annotations in your controller:
@RequestMapping(value = "/someUrl")
public String someMethod(String valueOne) {
//do stuff with valueOne variable here
}
Works with GET and POST
You need to call mediaPlayer.start()
in the onPrepared
method by using a listener.
You are getting this error because you are calling mediaPlayer.start()
before it has reached the prepared state.
Here is how you can do it :
mp.setDataSource(url);
mp.setOnPreparedListener(this);
mp.prepareAsync();
public void onPrepared(MediaPlayer player) {
player.start();
}
Mootools redefines preventDefault in Event objects. So your code should work fine on every browser. If it doesn't, then there's a problem with ie8 support in mootools.
Did you test your code on ie6 and/or ie7?
The doc says
Every event added with addEvent gets the mootools method automatically, without the need to manually instance it.
but in case it doesn't, you might want to try
new Event(event).preventDefault();
Put all the files (html and resources)in a directory (for my "manual"). Next, drag and drop the directory to XCode, over "Supporting Files". You should check the options "Copy Items if needed" and "Create folder references". Next, write a simple code:
NSURL *url = [[NSBundle mainBundle] URLForResource:@"manual/index" withExtension:@"html"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];
Attention to @"manual/index"
, manual is the name of my directory!!
It's all!!!! Sorry for my bad english...
=======================================================================
Hola desde Costa Rica. Ponga los archivos (html y demás recursos) en un directorio (en mi caso lo llamé manual), luego, arrastre y suelte en XCode, sobre "Supporting Files". Usted debe seleccionar las opciones "Copy Items if needed" y "Create folder references".
NSURL *url = [[NSBundle mainBundle] URLForResource:@"manual/index" withExtension:@"html"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];
Presta atención a @"manual/index"
, manual es el nombre de mi directorio!!
Save, then redefine the variable $_FILES to whatever you need. maybe not the best solution, but this worked for me.
function do_upload()
{
$this->load->library('upload');
$this->upload->initialize($this->set_upload_options());
$quantFiles = count($_FILES['userfile']['name']);
for($i = 0; $i < $quantFiles ; $i++)
{
$arquivo[$i] = array
(
'userfile' => array
(
'name' => $_FILES['userfile']['name'][$i],
'type' => $_FILES['userfile']['type'][$i],
'tmp_name' => $_FILES['userfile']['tmp_name'][$i],
'error' => $_FILES['userfile']['error'][$i],
'size' => $_FILES['userfile']['size'][$i]
)
);
}
for($i = 0; $i < $quantFiles ; $i++)
{
$_FILES = '';
$_FILES = $arquivo[$i];
if ( ! $this->upload->do_upload())
{
$error[$i] = array('error' => $this->upload->display_errors());
return FALSE;
}
else
{
$data[$i] = array('upload_data' => $this->upload->data());
var_dump($this->upload->data());
}
}
if(isset($error))
{
$this->index($error);
}
else
{
$this->index($data);
}
}
the separate function to establish the config..
private function set_upload_options()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'xml|pdf';
$config['max_size'] = '10000';
return $config;
}
Let's say the list is:
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
For this example. If I understand correctly, you want the list items to be in the middle of the screen, but you want the text IN those list items to be centered to the left of the list item itself. Doing that is actually pretty easy. You just need some CSS:
ul {
display: table;
margin: 0 auto;
text-align: left;
}
And it works! Here is what is happening. First, we say we want to affect only unordered lists. Then, we do Rafael Herscovici's trick for centering the list items. Finally, we say to align the text to the left of the list items.
Instead of disabled
, you could consider using readonly
. With some extra CSS you can style the input so it looks like an disabled
field.
There is actually another problem. The event change
only triggers when the element looses focus, which is not logic considering an disabled
field. Probably you are pushing data into this field from another call. To make this work you can use the event 'bind'.
$('form').bind('change', 'input', function () {
console.log('Do your thing.');
});
Ensure that all dependencies of your own dll are present near the dll, or in System32
.
To do this in Swift3 following is the code:
let labelSizeWithFixedWith = CGSize(width: 300, height: CGFloat.greatestFiniteMagnitude)
let exactLabelsize = self.label.sizeThatFits(labelSizeWithFixedWith)
self.label.frame = CGRect(origin: CGPoint(x: 20, y: 20), size: exactLabelsize)
That's one of most useless desires of beginner Android developers, and unfortunately it seems to be very popular. How do you define "close" an Android application? Hide it's user interface? Interrupt background work? Stop handling broadcasts?
Android applications are a set of modules, bundled in an .apk and exposed to the system trough AndroidManifest.xml. Activities can be arranged and re-arranged trough different task stacks, and finish()-ing or any other navigating away from a single Activity may mean totally different things in different situations. Single application can run inside multiple processes, so killing one process doesn't necessary mean there will be no application code left running. And finally, BroadcastReceivers can be called by the system any time, recreating the needed processes if they are not running.
The main thing is that you don't need to stop/kill/close/whatever your app trough a single line of code. Doing so is an indication you missed some important point in Android development. If for some bizarre reason you have to do it, you need to finish() all Activities, stop all Services and disable all BroadcastReceivers declared in AndroidManifest.xml. That's not a single line of code, and maybe launching the Activity that uninstalls your own application will do the job better.
This is the code from the accepted answer above, with some changes made regarding the Base64 encoding. The code below compiles.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
public class HttpBasicAuth {
public static void main(String[] args) {
try {
URL url = new URL ("http://ip:port/login");
Base64 b = new Base64();
String encoding = b.encodeAsString(new String("test1:test1").getBytes());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic " + encoding);
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in =
new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
The best approach depends on the expected key distribution and number of collisions. If relatively few collisions are expected, it really doesn't matter which method is used. If lots of collisions are expected, then which to use depends on the cost of rehashing or probing vs. manipulating the extensible bucket data structure.
But here is source code example of An Hashmap Implementation in C
What you're looking for is n choose k. Basically:
For every pair of 100 items, you'd have 4,950 combinations - provided order doesn't matter (AB and BA are considered a single combination) and you don't want to repeat (AA is not a valid pair).
Sometimes that problem occurs if you already have a branch with the base name.
I tried this:
git checkout -b features/aName origin/features/aName
Unfortunately, I already had a branch named features
, and I got the exception of the question asker.
Removing the branch features
resolved the problem, the above command worked.
simple one:
[[@"first" stringByAppendingString:@"second"] stringByAppendingString:@"third"];
if you have many STRINGS to Concatenate, you should use NSMutableString
for better performance
You can't do this with plain vanilla HTML, so JSF can't do much for you here as well.
If you're targeting decent browsers only, then just make use of CSS3:
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<label class="unselectable">Unselectable label</label>
If you'd like to cover older browsers as well, then consider this JavaScript fallback:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2310734</title>
<script>
window.onload = function() {
var labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
disableSelection(labels[i]);
}
};
function disableSelection(element) {
if (typeof element.onselectstart != 'undefined') {
element.onselectstart = function() { return false; };
} else if (typeof element.style.MozUserSelect != 'undefined') {
element.style.MozUserSelect = 'none';
} else {
element.onmousedown = function() { return false; };
}
}
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
If you're already using jQuery, then here's another example which adds a new function disableSelection()
to jQuery so that you can use it anywhere in your jQuery code:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2310734 with jQuery</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.fn.extend({
disableSelection: function() {
this.each(function() {
if (typeof this.onselectstart != 'undefined') {
this.onselectstart = function() { return false; };
} else if (typeof this.style.MozUserSelect != 'undefined') {
this.style.MozUserSelect = 'none';
} else {
this.onmousedown = function() { return false; };
}
});
}
});
$(document).ready(function() {
$('label').disableSelection();
});
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
This blog post gives a nice explanation and some background. Basically, the "permanent generation" (whose size is given by PermSize) is used to store things that the JVM has to allocate space for, but which will not (normally) be garbage-collected (hence "permanent") (+). That means for example loaded classes and static fields.
There is also a FAQ on garbage collection directly from Sun, which answers some questions about the permanent generation. Finally, here's a blog post with a lot of technical detail.
(+) Actually parts of the permanent generation will be GCed, e.g. class objects will be removed when a class is unloaded. But that was uncommon when the permanent generation was introduced into the JVM, hence the name.
I am not sure if this is the correct solution but I have achieved this by redefining .marquee class just after animation CSS.
Check below:
<style>
#marquee-wrapper{
width:700px;
display:block;
border:1px solid red;
}
div.marquee{
width:100px;
height:100px;
background:red;
position:relative;
animation:myfirst 5s;
-moz-animation:myfirst 5s; /* Firefox */
}
@-moz-keyframes myfirst /* Firefox */{
0% {background:red; left:0px; top:0px;}
100% {background:red; left:100%; top:0px}
}
div.marquee{
left:700px; top:0px
}
</style>
<!-- HTMl COde -->
<p><b>Note:</b> This example does not work in Internet Explorer and Opera.</p>
<div id="marquee-wrapper">
<div class="marquee"></div>
I found this thread looking to create an ajax page refresh button with jQuery Mobile.
@sgissinger had the closest answer to what I was looking for, but it was outdated.
I updated for jQuery Mobile 1.4
function refreshPage() {
jQuery.mobile.pageContainer.pagecontainer('change', window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
// 'reload' parameter not working yet: //github.com/jquery/jquery-mobile/issues/7406
});
}
// Run it with .on
$(document).on( "click", '#refresh', function() {
refreshPage();
});
There are several ways to prevent line breaks in content. Using
is one way, and works fine between words, but using it between an empty element and some text does not have a well-defined effect. The same would apply to the more logical and more accessible approach where you use an image for an icon.
The most robust alternative is to use nobr
markup, which is nonstandard but universally supported and works even when CSS is disabled:
<td><nobr><i class="flag-bfh-ES"></i> +34 666 66 66 66</nobr></td>
(You can, but need not, use
instead of spaces in this case.)
Another way is the nowrap
attribute (deprecated/obsolete, but still working fine, except for some rare quirks):
<td nowrap><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>
Then there’s the CSS way, which works in CSS enabled browsers and needs a bit more code:
<style>
.nobr { white-space: nowrap }
</style>
...
<td class=nobr><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>
Use:
/*/ITEM[starts-with(REVENUE_YEAR,'2552')]/REGION
Note: Unless your host language can't handle element instance as result, do not use text nodes specially in mixed content data model. Do not start expressions with //
operator when the schema is well known.
They are all the same in the work they do. You can do the same things using any of them. But for readability, usability, convenience etc., they differ.
If you don't want to add a new dependency just to do this (like HTMLEntities
) and you're already using Hpricot
, it can both escape and unescape for you. It handles much more than CGI
:
Hpricot.uxs "foo bär"
=> "foo bär"
I imagine that you define your image something like this:
<img id="image_portrait" src="" alt="chef etat" width="120" height="135" />
You can simply load/update image for this tag and chage/set atts (width,height):
var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);
How about that?
<?php
while($items = array_pop($lists)){
echo "<ul>";
foreach($items as $item){
echo "<li>$item</li>";
}
echo "</ul>";
}
?>
I got this issue when the Virtualbox had the wrong networking. I've updated to NAT and was able to get on internet and download packages from us.archive.ubuntu.com
if( "mystring#".substr(-1) === "#" ) {}
sudo dpkg-reconfigure -plow phpmyadmin
Select No when asked to reconfigure the database. Then when asked to choose apache2, make sure to hit space while [ ] apache2 is highlighted. An asterisk should appear between the brackets. Then hit Enter. Phpmyadmin should reconfigure and now http://localhost/phpmyadmin should work. for further detail https://www.howtoforge.com/installing-apache2-with-php5-and-mysql-support-on-ubuntu-13.04-lamp
Could it work if you count them, and then add a limit to your delete query leaving just one?
For example, if you have two or more, write your query like this:
DELETE FROM table WHERE SID = 1 LIMIT 1;
The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.
Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.
If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/
is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/
or http://s3-external-1.amazonaws.com/bucket/
.¹
The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].
S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com
. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.
If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.
However... the two endpoints do not offer the same functionality.
Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.
Choose the correct type of endpoint (REST or web site) for your application:
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff
¹ s3-external-1.amazonaws.com
has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com
. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2
had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1
so s3-external-2
appears to have no purpose except backwards-compatibility.
Actually you don't even need the block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open(playlist_name, 'w').puts(music)
The legend titles can be labeled by specific aesthetic.
This can be achieved using the guides()
or labs()
functions from ggplot2
(more here and here). It allows you to add guide/legend properties using the aesthetic mapping.
Here's an example using the mtcars
data set and labs()
:
ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
geom_point() +
labs(x="miles per gallon", y="displacement", size="horsepower",
col="# of cylinders", shape="# of gears")
Answering the OP's question using guides()
:
# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")
# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) +
geom_point(size=5) +
labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
guides(color=guide_legend("my title")) # add guide properties by aesthetic
Faroo has a free Web Search API
i Have face the same issue and resolved by replacing the old Oracle.DataAccess.dll with new Oracle.DataAccess.dll(which come with oracle client when install)
in my case the path of new Oracle.DataAccess.dll is
According to the official ReactJs documentation, you need to pass argument in the default format witch is:
P = {} // default for your props
S = {} // default for yout state
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
Or to define your own type like below: (just an exp)
interface IProps {
clients: Readonly<IClientModel[]>;
onSubmit: (data: IClientModel) => void;
}
interface IState {
clients: Readonly<IClientModel[]>;
loading: boolean;
}
class ClientsPage extends React.Component<IProps, IState> {
// ...
}
Eventhough it is an old question, this may help someone.
We can choose multiple files while browsing for a file using "multiple"
<input type="file" name="datafile" size="40" multiple>
You can check if an object is nil (null) by calling present? or blank? .
@object.present?
this will return false if the project is an empty string or nil .
or you can use
@object.blank?
this is the same as present? with a bang and you can use it if you don't like 'unless'. this will return true for an empty string or nil .
Try to use sudo, to run asterisk -r that works for me every time this error comes up.
If you append this to user.js
:
exports.User = User;
then in server.js
you can do:
var userFile = require('./user.js');
var User = userFile.User;
http://nodejs.org/docs/v0.4.10/api/globals.html#require
Another way is:
global.User = User;
then this would be enough in server.js
:
require('./user.js');
On Mac OS X, for anyone having:
-bash: /usr/local/bin/composer: Permission denied
problem, while trying to move downloaded composer.phar
using:
mv composer.phar /usr/local/bin/composer
this is the cause:
System Integrity Protection
and this is the solution:
csrutil disable
and hit enter. You should see a msg returned saying that:
the System Integrity Protection is off.
/usr/bin
and NOT /usr/local/bin
because for some reason it just didn't work there.csrutil enable
The above 6 steps are copied from here, so all the credit belongs to the user Vasheer there.
Could you provide a whole makefile? But right now I can tell - you should check that "install" target already exists. So, check Makefile whether it contains a
install: (anything there)
line. If not, there is no such target and so make has right. Probably you should use just "make" command to compile and then use it as is or install yourself, manually.
Install is not any standard of make, it is just a common target, that could exists, but not necessary.
Just do Eclipse> Project > Clean and then run the test cases again. It should work.
What it does in background is, that it will call mvn eclipse:clean in your project directory which will delete your .project and .classpath files and you can also do a mvn eclipse:eclipse - this regenerates your .project and .classpath files. Thus adding the desired class in the classpath.
This is another way to shuffle the data.frame
using package dplyr
:
row-wise:
df2 <- slice(df1, sample(1:n()))
or
df2 <- sample_frac(df1, 1L)
column-wise:
df2 <- select(df1, one_of(sample(names(df1))))
If you are trying to decipher info MS puts on their patching site such as https://technet.microsoft.com/en-us/library/security/ms17-010.aspx
you will need a combo such as:
$name=(Get-WmiObject Win32_OperatingSystem).caption
$bit=(Get-WmiObject Win32_OperatingSystem).OSArchitecture
$ver=(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ReleaseId
Write-Host $name, $bit, $ver
Microsoft Windows 10 Home 64-bit 1703
If you just want a button to open up a new window, then something like this works:
btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Parent root;
try {
root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
Stage stage = new Stage();
stage.setTitle("My New Stage Title");
stage.setScene(new Scene(root, 450, 450));
stage.show();
// Hide this current window (if this is what you want)
((Node)(event.getSource())).getScene().getWindow().hide();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
This problem usually happen if eclipse accidentally compile the main.xml incorrectly. The easiest solution is to delete R.java inside gen directory. Once we delete, than eclipse will generate the new R.java base on the latest main.xml
As of Aug 29, 2013, Github's documentation claim that:
Warning: Project pages subpaths like http://username.github.io/projectname will not be redirected to a project's custom domain.
The value
attribute on submit
-type <input>
elements controls the text displayed.
<input type="submit" class="like" value="Like" />
The answers above point out how the block size can impact performance and suggest a common heuristic for its choice based on occupancy maximization. Without wanting to provide the criterion to choose the block size, it would be worth mentioning that CUDA 6.5 (now in Release Candidate version) includes several new runtime functions to aid in occupancy calculations and launch configuration, see
CUDA Pro Tip: Occupancy API Simplifies Launch Configuration
One of the useful functions is cudaOccupancyMaxPotentialBlockSize
which heuristically calculates a block size that achieves the maximum occupancy. The values provided by that function could be then used as the starting point of a manual optimization of the launch parameters. Below is a little example.
#include <stdio.h>
/************************/
/* TEST KERNEL FUNCTION */
/************************/
__global__ void MyKernel(int *a, int *b, int *c, int N)
{
int idx = threadIdx.x + blockIdx.x * blockDim.x;
if (idx < N) { c[idx] = a[idx] + b[idx]; }
}
/********/
/* MAIN */
/********/
void main()
{
const int N = 1000000;
int blockSize; // The launch configurator returned block size
int minGridSize; // The minimum grid size needed to achieve the maximum occupancy for a full device launch
int gridSize; // The actual grid size needed, based on input size
int* h_vec1 = (int*) malloc(N*sizeof(int));
int* h_vec2 = (int*) malloc(N*sizeof(int));
int* h_vec3 = (int*) malloc(N*sizeof(int));
int* h_vec4 = (int*) malloc(N*sizeof(int));
int* d_vec1; cudaMalloc((void**)&d_vec1, N*sizeof(int));
int* d_vec2; cudaMalloc((void**)&d_vec2, N*sizeof(int));
int* d_vec3; cudaMalloc((void**)&d_vec3, N*sizeof(int));
for (int i=0; i<N; i++) {
h_vec1[i] = 10;
h_vec2[i] = 20;
h_vec4[i] = h_vec1[i] + h_vec2[i];
}
cudaMemcpy(d_vec1, h_vec1, N*sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(d_vec2, h_vec2, N*sizeof(int), cudaMemcpyHostToDevice);
float time;
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord(start, 0);
cudaOccupancyMaxPotentialBlockSize(&minGridSize, &blockSize, MyKernel, 0, N);
// Round up according to array size
gridSize = (N + blockSize - 1) / blockSize;
cudaEventRecord(stop, 0);
cudaEventSynchronize(stop);
cudaEventElapsedTime(&time, start, stop);
printf("Occupancy calculator elapsed time: %3.3f ms \n", time);
cudaEventRecord(start, 0);
MyKernel<<<gridSize, blockSize>>>(d_vec1, d_vec2, d_vec3, N);
cudaEventRecord(stop, 0);
cudaEventSynchronize(stop);
cudaEventElapsedTime(&time, start, stop);
printf("Kernel elapsed time: %3.3f ms \n", time);
printf("Blocksize %i\n", blockSize);
cudaMemcpy(h_vec3, d_vec3, N*sizeof(int), cudaMemcpyDeviceToHost);
for (int i=0; i<N; i++) {
if (h_vec3[i] != h_vec4[i]) { printf("Error at i = %i! Host = %i; Device = %i\n", i, h_vec4[i], h_vec3[i]); return; };
}
printf("Test passed\n");
}
EDIT
The cudaOccupancyMaxPotentialBlockSize
is defined in the cuda_runtime.h
file and is defined as follows:
template<class T>
__inline__ __host__ CUDART_DEVICE cudaError_t cudaOccupancyMaxPotentialBlockSize(
int *minGridSize,
int *blockSize,
T func,
size_t dynamicSMemSize = 0,
int blockSizeLimit = 0)
{
return cudaOccupancyMaxPotentialBlockSizeVariableSMem(minGridSize, blockSize, func, __cudaOccupancyB2DHelper(dynamicSMemSize), blockSizeLimit);
}
The meanings for the parameters is the following
minGridSize = Suggested min grid size to achieve a full machine launch.
blockSize = Suggested block size to achieve maximum occupancy.
func = Kernel function.
dynamicSMemSize = Size of dynamically allocated shared memory. Of course, it is known at runtime before any kernel launch. The size of the statically allocated shared memory is not needed as it is inferred by the properties of func.
blockSizeLimit = Maximum size for each block. In the case of 1D kernels, it can coincide with the number of input elements.
Note that, as of CUDA 6.5, one needs to compute one's own 2D/3D block dimensions from the 1D block size suggested by the API.
Note also that the CUDA driver API contains functionally equivalent APIs for occupancy calculation, so it is possible to use cuOccupancyMaxPotentialBlockSize
in driver API code in the same way shown for the runtime API in the example above.
AFAIK, both substring()
and indexOf()
are supported by both Mozilla and IE. However, note that substr() might not be supported on earlier versions of some browsers (esp. Netscape/Opera).
Your post indicates that you already know how to do it using substring()
and indexOf()
, so I'm not posting a code sample.
Two ways. Either create a button and style it so it looks like a link with css, or create a link and use onclick="this.closest('form').submit();return false;"
.
Include a few #ifndef name #define name #endif preprocessor that should solve your problem. The issue is it going from the header to the function then back to the header so it is redefining the class with all the preprocessor(#include) multiple times.
If any of these characters, '>', '<', '|' or '*', are used, a single or double quotes must be used
conda install [-y] package">=version"
conda install [-y] package'>=low_version, <=high_version'
conda install [-y] "package>=low_version, <high_version"
conda install -y torchvision">=0.3.0"
conda install openpyxl'>=2.4.10,<=2.6.0'
conda install "openpyxl>=2.4.10,<3.0.0"
where option -y, --yes Do not ask for confirmation.
Here is a summary:
Format Sample Specification Results
Exact qtconsole==4.5.1 4.5.1
Fuzzy qtconsole=4.5 4.5.0, 4.5.1, ..., etc.
>=, >, <, <= "qtconsole>=4.5" 4.5.0 or higher
qtconsole"<4.6" less than 4.6.0
OR "qtconsole=4.5.1|4.5.2" 4.5.1, 4.5.2
AND "qtconsole>=4.3.1,<4.6" 4.3.1 or higher but less than 4.6.0
Potion of the above information credit to Conda Cheat Sheet
Tested on conda 4.7.12
You can also get the colors from your resources by using:
dateView.setDivider(new ColorDrawable(_context.getResources().getColor(R.color.textlight)));
dateView.setDividerHeight(1);
This works:
myElement.className = 'foo bar baz';
In SSMS, "Query" menu item... "Results to"... "Results to File"
Shortcut = CTRL+shift+F
You can set it globally too
"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down
Edit: after comment
In SSMS, "Query" menu item... "SQLCMD" mode
This allows you to run "command line" like actions.
A quick test in my SSMS 2008
:OUT c:\foo.txt
SELECT * FROM sys.objects
Edit, Sep 2012
:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects
docker build -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .
You can use the str.split
method: string.split('__')
>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']
clone()
creates a shallow copy. Which means the elements will not be cloned. (What if they didn't implement Cloneable
?)
You may want to use Arrays.copyOf(..)
for copying arrays instead of clone()
(though cloning is fine for arrays, unlike for anything else)
If you want deep cloning, check this answer
A little example to illustrate the shallowness of clone()
even if the elements are Cloneable
:
ArrayList[] array = new ArrayList[] {new ArrayList(), new ArrayList()};
ArrayList[] clone = array.clone();
for (int i = 0; i < clone.length; i ++) {
System.out.println(System.identityHashCode(array[i]));
System.out.println(System.identityHashCode(clone[i]));
System.out.println(System.identityHashCode(array[i].clone()));
System.out.println("-----");
}
Prints:
4384790
4384790
9634993
-----
1641745
1641745
11077203
-----
'ProgramFiles(x86)' is an environment variable automatically defined by cmd.exe (both 32-bit and 64-bit versions) on Windows 64-bit machines only, so try this:
@ECHO OFF
echo Check operating system ...
if defined PROGRAMFILES(X86) (
echo 64-bit sytem detected
) else (
echo 32-bit sytem detected
)
pause
Installing jdk1.8.0_211 and setting the below variable in product.conf (located in C:\Users\\AppData\Roaming\sqldeveloper\19.1.0) to JDK8 home worked for me
SetJavaHome D:\jdk1.8.0_211
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
Finally got the solution here - https://stackoverflow.com/a/49663101/9640177
implementation files('libs/aar-file.aar')
Edit I had one more complication - I had set minifyEnabled true for the library module.
I found a bit different cause of the error. It seems like SQLite wants to use correct primary key class property name. So...
Wrong PK name
public class Client
{
public int SomeFieldName { get; set; } // It is the ID
...
}
Correct PK name
public class Client
{
public int Id { get; set; } // It is the ID
...
}
public class Client
{
public int ClientId { get; set; } // It is the ID
...
}
It still posible to use wrong PK name but we have to use [Key] attribute like
public class Client
{
[Key]
public int SomeFieldName { get; set; } // It is the ID
...
}
for rails
db = ActiveRecord::Base.connection.raw_connection
db.create_function('regexp', 2) do |func, pattern, expression|
func.result = expression.to_s.match(Regexp.new(pattern.to_s, Regexp::IGNORECASE)) ? 1 : 0
end
For folks who find this posting through the search engines, another possible cause of this problem is from importing the wrong package version of @Transient
. Make sure that you import javax.persistence.transient
and not some other package.
When asked:
Are you sure you want to continue connecting (yes/no)?
Type yes as the response
That is how I solved my issue. But if you try to just hit the enter button, it won't work!
Alternatively to Martin's answer, you could also add the INTO part at the end of the query to make the query more readable:
SELECT Id, dateCreated FROM products INTO iId, dCreate
You can also specify a dependency not in a maven repository. Could be usefull when no central maven repository for your team exist or if you have a CI server
<dependency>
<groupId>com.stackoverflow</groupId>
<artifactId>commons-utils</artifactId>
<version>1.3</version>
<scope>system</scope>
<systemPath>${basedir}/lib/commons-utils.jar</systemPath>
</dependency>
returning true or false indicates that whether execution should continue or stop right there. So just an example
<input type="button" onclick="return func();" />
Now if func() is defined like this
function func()
{
// do something
return false;
}
the click event will never get executed. On the contrary if return true is written then the click event will always be executed.
Sorry I didn't see your Java tag, was reading question only. I'll leave my other answers here anyway since I've typed them out.
Java
String myString = "9Hello World!";
if ( Character.isDigit(myString.charAt(0)) )
{
System.out.println("String begins with a digit");
}
C++:
string myString = "2Hello World!";
if (isdigit( myString[0]) )
{
printf("String begins with a digit");
}
Regular expression:
\b[0-9]
Please try this piece of code..
<TextView
android:id="@+id/txtview1"
android:layout_width="wrap_content"
android:background="@drawable/bg_task"
android:layout_height="wrap_content"
android:textSize="14sp"
android:singleLine="true"
android:textColor="#FFFFFF" />
Used background image as transparent so may be solved that.
OR
android:background="#07000000"
OR
Please try below ...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="center_horizontal" android:orientation="vertical"
android:background="@drawable/main_bg">
<ImageView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/header"
android:src="@drawable/btn_complete" />
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/list" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_weight="1"
android:paddingRight="5dp" android:scrollbarStyle="outsideOverlay"
android:cacheColorHint="#00000000" />
<TextView android:id="@+id/footer" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="25sp"
android:singleLine="true" android:background="#07000000"
android:textColor="#FFFFFF" android:text="rrrrr"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</LinearLayout>
you can use the serializable objects in the intents but at the time of making serialize a Parcelable object it can give a serious exception like NotSerializableException. Is it not recommended using serializable with Parcelable . So it is better to extends Parcelable with the object that you want to use with bundle and intents. As this Parcelable is android specific so it doesn't have any side effects. :)
You need to have a byte[] in your DB.
My byte[] is in my Person object:
public class Person
{
public byte[] Image { get; set; }
}
You need to convert your byte[] in a String. So, I have in my controller :
String img = Convert.ToBase64String(person.Image);
Next, in my .cshtml file, my Model is a ViewModel. This is what I have in :
public String Image { get; set; }
I use it like this in my .cshtml file:
<img src="@String.Format("data:image/jpg;base64,{0}", Model.Image)" />
"data:image/image file extension;base64,{0}, your image String"
I wish it will help someone !
I encountered this exception in WebLogic, turns out it is a bug in WebLogic. Please see here for more details: Spring Boot exception: Could not open ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]
do you called the ViewTreeObserver and not remove it.
mEtEnterlive.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// do nothing here can cause such problem
});
Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.
Use the typedef
specifier to avoid re-using the struct
statement everytime you declare a struct variable:
typedef struct
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
}Body;
Then declare your array of structs. Initialization of each element goes along with the declaration:
Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};
To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.
the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind
/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
EmpID int,
Activity varchar(20),
DoneBy varchar(50),
Date_Time datetime NOT NULL DEFAULT GETDATE()
);
select * from Emp_Audit*/
create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
SET @activity = 'UPDATE';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from inserted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end
If exists (Select * from inserted) and not exists(Select * from deleted)
begin
SET @activity = 'INSERT';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from inserted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end
If exists(select * from deleted) and not exists(Select * from inserted)
begin
SET @activity = 'DELETE';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from deleted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end
In C++11 you could also create an alias for convenience:
template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
And use it like this:
min_heap<int> my_heap;
I guess you want to use Array.prototype.find Find will break itself when it finds your specific value in the array.
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries));
// { name: 'cherries', quantity: 5 }
In your case
var KeyVal = string.split(", ");
var obj = {};
var i;
for (i in KeyVal) {
KeyVal[i] = KeyVal[i].split(":");
obj[eval(KeyVal[i][0])] = eval(KeyVal[i][1]);
}
Most of the time a combination of fgets
and sscanf
does the job. The other thing would be to write your own parser, if the input is well formatted. Also note your second example needs a bit of modification to be used safely:
#define LENGTH 42
#define str(x) # x
#define xstr(x) str(x)
/* ... */
int nc = scanf("%"xstr(LENGTH)"[^\n]%*[^\n]", array);
The above discards the input stream upto but not including the newline (\n
) character. You will need to add a getchar()
to consume this. Also do check if you reached the end-of-stream:
if (!feof(stdin)) { ...
and that's about it.
.NET 4.5 is an in place replacement for 4.0 - you will find the assemblies in the 4.0 directory.
See the blogs by Rick Strahl and Scott Hanselman on this topic.
You can also find the specific versions in:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework
Try PyPDF2.
There is a good tutorial here: https://automatetheboringstuff.com/chapter13/
.each()
should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map
.
var newArray = $(array).map(function(i) {
return $('#event' + i, response).html();
});
Edit: I removed the adding of the prepended 0 since it is suggested to not use that.
If you must have it use
var newArray = $(array).map(function(i) {
var number = '' + i;
if (number.length == 1) {
number = '0' + number;
}
return $('#event' + number, response).html();
});
The RelativeLayout
(i.e. the ViewParent
) should have a resource Id defined in the layout file (for example, android:id=@+id/myParentViewId
). If you don't do that, the call to getId will return null. Look at this answer for more info.
Deadlocks will only occur when you have two or more locks that can be aquired at the same time and they are grabbed in different order.
Ways to avoid having deadlocks are:
When you export a class module and open the file in Notepad, you'll notice, near the top, a bunch of hidden attributes (the VBE doesn't display them, and doesn't expose functionality to tweak most of them either). One of them is VB_PredeclaredId
:
Attribute VB_PredeclaredId = False
Set it to True
, save, and re-import the module into your VBA project.
Classes with a PredeclaredId
have a "global instance" that you get for free - exactly like UserForm
modules (export a user form, you'll see its predeclaredId attribute is set to true).
A lot of people just happily use the predeclared instance to store state. That's wrong - it's like storing instance state in a static class!
Instead, you leverage that default instance to implement your factory method:
[Employee
class]
'@PredeclaredId
Option Explicit
Private Type TEmployee
Name As String
Age As Integer
End Type
Private this As TEmployee
Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As Employee
With New Employee
.Name = emplName
.Age = emplAge
Set Create = .Self 'returns the newly created instance
End With
End Function
Public Property Get Self() As Employee
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Age() As String
Age = this.Age
End Property
Public Property Let Age(ByVal value As String)
this.Age = value
End Property
With that, you can do this:
Dim empl As Employee
Set empl = Employee.Create("Johnny", 69)
Employee.Create
is working off the default instance, i.e. it's considered a member of the type, and invoked from the default instance only.
Problem is, this is also perfectly legal:
Dim emplFactory As New Employee
Dim empl As Employee
Set empl = emplFactory.Create("Johnny", 69)
And that sucks, because now you have a confusing API. You could use '@Description
annotations / VB_Description
attributes to document usage, but without Rubberduck there's nothing in the editor that shows you that information at the call sites.
Besides, the Property Let
members are accessible, so your Employee
instance is mutable:
empl.Name = "Jane" ' Johnny no more!
The trick is to make your class implement an interface that only exposes what needs to be exposed:
[IEmployee
class]
Option Explicit
Public Property Get Name() As String : End Property
Public Property Get Age() As Integer : End Property
And now you make Employee
implement IEmployee
- the final class might look like this:
[Employee
class]
'@PredeclaredId
Option Explicit
Implements IEmployee
Private Type TEmployee
Name As String
Age As Integer
End Type
Private this As TEmployee
Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As IEmployee
With New Employee
.Name = emplName
.Age = emplAge
Set Create = .Self 'returns the newly created instance
End With
End Function
Public Property Get Self() As IEmployee
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Age() As String
Age = this.Age
End Property
Public Property Let Age(ByVal value As String)
this.Age = value
End Property
Private Property Get IEmployee_Name() As String
IEmployee_Name = Name
End Property
Private Property Get IEmployee_Age() As Integer
IEmployee_Age = Age
End Property
Notice the Create
method now returns the interface, and the interface doesn't expose the Property Let
members? Now calling code can look like this:
Dim empl As IEmployee
Set empl = Employee.Create("Immutable", 42)
And since the client code is written against the interface, the only members empl
exposes are the members defined by the IEmployee
interface, which means it doesn't see the Create
method, nor the Self
getter, nor any of the Property Let
mutators: so instead of working with the "concrete" Employee
class, the rest of the code can work with the "abstract" IEmployee
interface, and enjoy an immutable, polymorphic object.
With me was the same problem, but it was caused, because i was using the mysql server on 32 (bit) and the workbench was running on 64(bit) version. the server and the workbench need to has the same version.
I got this error generating a data frame consisting of timestamps and data:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))
Adding the suggested solution works for me:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))
Thanks Chang She!
Example:
data
2005-01-01 00:10:00 7.53
2005-01-01 00:20:00 7.54
2005-01-01 00:30:00 7.62
2005-01-01 00:40:00 7.68
2005-01-01 00:50:00 7.81
2005-01-01 01:00:00 7.95
2005-01-01 01:10:00 7.96
2005-01-01 01:20:00 7.95
2005-01-01 01:30:00 7.98
2005-01-01 01:40:00 8.06
2005-01-01 01:50:00 8.04
2005-01-01 02:00:00 8.06
2005-01-01 02:10:00 8.12
2005-01-01 02:20:00 8.12
2005-01-01 02:30:00 8.25
2005-01-01 02:40:00 8.27
2005-01-01 02:50:00 8.17
2005-01-01 03:00:00 8.21
2005-01-01 03:10:00 8.29
2005-01-01 03:20:00 8.31
2005-01-01 03:30:00 8.25
2005-01-01 03:40:00 8.19
2005-01-01 03:50:00 8.17
2005-01-01 04:00:00 8.18
data
2005-01-01 00:00:00 7.636000
2005-01-01 01:00:00 7.990000
2005-01-01 02:00:00 8.165000
2005-01-01 03:00:00 8.236667
2005-01-01 04:00:00 8.180000
There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
Here is what you can do:
#include <algorithm>
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
However, in C++0x, you can do this:
std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};
Of course, if you choose to use std::vector
instead of raw array.
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
have you considered using a LinkedHashMap<>()..?
public static void main(String[] args) {
Map<Object, Object> handler = new LinkedHashMap<Object, Object>();
handler.put("item", "Value");
handler.put(2, "Movies");
handler.put("isAlive", true);
for (Map.Entry<Object, Object> entrY : handler.entrySet())
System.out.println(entrY.getKey() + ">>" + entrY.getValue());
List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>();
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> a,
Map.Entry<String, Integer> b) {
return a.getValue().compareTo(b.getValue());
}
});
}
results into an organized linked object.
item>>Value
2>>Movies
isAlive>>true
check the sorting part picked from here..
I have solved this problem by using the following code segment:
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
boolean max = jTextField1.getText().length() > 4;
if ( max ){
evt.consume();
}
}
You can use groupBy of angular.filter module.
so you can do something like this:
JS:
$scope.players = [
{name: 'Gene', team: 'alpha'},
{name: 'George', team: 'beta'},
{name: 'Steve', team: 'gamma'},
{name: 'Paula', team: 'beta'},
{name: 'Scruath', team: 'gamma'}
];
HTML:
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
Group name: {{ key }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>
RESULT:
Group name: alpha
* player: Gene
Group name: beta
* player: George
* player: Paula
Group name: gamma
* player: Steve
* player: Scruath
UPDATE: jsbin Remember the basic requirements to use angular.filter
, specifically note you must add it to your module's dependencies:
(1) You can install angular-filter using 4 different methods:
- clone & build this repository
- via Bower: by running $ bower install angular-filter from your terminal
- via npm: by running $ npm install angular-filter from your terminal
- via cdnjs http://www.cdnjs.com/libraries/angular-filter
(2) Include angular-filter.js (or angular-filter.min.js) in your index.html, after including Angular itself.
(3) Add 'angular.filter' to your main module's list of dependencies.
Create a file with the name of your helper in /application/helpers and add it to the autoload config file/load it manually.
E.g. place a file called user_helper.php in /application/helpers with this content:
<?php
function pre($var)
{
echo '<pre>';
if(is_array($var)) {
print_r($var);
} else {
var_dump($var);
}
echo '</pre>';
}
?>
Now you can either load the helper via $this->load->helper(‘user’);
or add it to application/config/autoload.php config.
You can also use ng-template, I think that would be more efficient while run time :)
<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
<div>2</div>
</ng-template>
Cheers
Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).
The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.
Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).
For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.
In bootstrap 3, this works well for me:
.btn-link.btn-anchor {
outline: none !important;
padding: 0;
border: 0;
vertical-align: baseline;
}
Used like:
<button type="button" class="btn-link btn-anchor">My Button</button>
I usually use keys
and I can't think of the last time I used or read a use of each
.
Don't forget about map
, depending on what you're doing in the loop!
map { print "$_ => $hash{$_}\n" } keys %hash;
Try this:
private byte[] Hex2Bin(string hex)
{
if ((hex == null) || (hex.Length < 1)) {
return new byte[0];
}
int num = hex.Length / 2;
byte[] buffer = new byte[num];
num *= 2;
for (int i = 0; i < num; i++) {
int num3 = int.Parse(hex.Substring(i, 2), NumberStyles.HexNumber);
buffer[i / 2] = (byte) num3;
i++;
}
return buffer;
}
private string Bin2Hex(byte[] binary)
{
StringBuilder builder = new StringBuilder();
foreach(byte num in binary) {
if (num > 15) {
builder.AppendFormat("{0:X}", num);
} else {
builder.AppendFormat("0{0:X}", num); /////// ?? 15 ???? 0
}
}
return builder.ToString();
}
Edit:
Well, he edited his post.
If an Object inherits Iterable, you are given the ability to use the for-each loop as such:
for(Object object : objectListVar) {
//code here
}
So in your case, if you wanted to update your Guns and their Bullets:
for(Gun g : guns) {
//invoke any methods of each gun
ArrayList<Bullet> bullets = g.getBullets()
for(Bullet b : bullets) {
System.out.println("X: " + b.getX() + ", Y: " + b.getY());
//update, check for collisions, etc
}
}
First get your third Gun object:
Gun g = gunList.get(2);
Then iterate over the third gun's bullets:
ArrayList<Bullet> bullets = g.getBullets();
for(Bullet b : bullets) {
//necessary code here
}
In my case, the problem was caused by some Response.Write commands at Master Page of the website (code behind). They were there only for debugging purposes (that's not the best way, I know)...
You just need this:
$(".hidden").attr("placeholder", "Type here to search");
classList
is used for manipulating classes and not attributes.
first hit for "java file exists" on google:
import java.io.*;
public class FileTest {
public static void main(String args[]) {
File f = new File(args[0]);
System.out.println(f + (f.exists()? " is found " : " is missing "));
}
}
Use CRTL+BREAK to suspend execution at any point. You will be put into break mode and can press F5 to continue the execution or F8 to execute the code step-by-step in the visual debugger.
Of course this only works when there is no message box open, so if your VBA code constantly opens message boxes for some reason it will become a little tricky to press the keys at the right moment.
You can even edit most of the code while it is running.
Use Debug.Print
to print out messages to the Immediate Window in the VBA editor, that's way more convenient than MsgBox
.
Use breakpoints or the Stop
keyword to automatically halt execution in interesting areas.
You can use Debug.Assert
to halt execution conditionally.
The methods do not have to give the same answers. That depends on which objects/classes you call them.
If you are implementing your own classes which you know you want to compare at some stage, you may have them implement the Comparable interface and implement the compareTo() method accordingly.
If you are using some classes from an API which do not implement the Comparable interface, but you still want to compare them. I.e. for sorting. You may create your own class which implements the Comparator interface and in its compare() method you implement the logic.
<input name="isActive" id="isActive" type="checkbox" value="1" checked="checked" onclick="return false"/>
$destroy
can refer to 2 things: method and event
.directive("colorTag", function(){
return {
restrict: "A",
scope: {
value: "=colorTag"
},
link: function (scope, element, attrs) {
var colors = new App.Colors();
element.css("background-color", stringToColor(scope.value));
element.css("color", contrastColor(scope.value));
// Destroy scope, because it's no longer needed.
scope.$destroy();
}
};
})
See @SunnyShah's answer.
The use of Swift 3 @objc inference in Swift 4 mode is deprecated?
use func call @objc
func call(){
foo()
}
@objc func foo() {
}
Replacing ScrollView with NestedScrollView resulted into smooth scrolling to the bottom.
Try this to detect the Enter key pressed.
$(document).on("keypress", function(e){
if(e.which == 13){
alert("You've pressed the enter key!");
}
});
See demo @ detect enter key press on keyboard
If your xml is written by java.lang.String
you can just using HttpClient
in this way
public void post() throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
}
pay attention to the Exceptions.
BTW, the example is written by the httpclient version 4.x
To get base URL in MVC even with subdomain www.somedomain.com/subdomain
:
var url = $"{Request.Url.GetLeftPart(UriPartial.Authority)}{Url.Content("~/")}";
I think you're looking for;
string[] skus = myLines.Select(x => x.Sku).ToArray();
However, if you're going to iterate over the sku's in subsequent code I recommend not using the ToArray()
bit as it forces the queries execution prematurely and makes the applications performance worse. Instead you can just do;
var skus = myLines.Select(x => x.Sku); // produce IEnumerable<string>
foreach (string sku in skus) // forces execution of the query
It's OK to run Docker-in-Docker (DinD) and in fact Docker (the company) has an official DinD image for this.
The caveat however is that it requires a privileged container, which depending on your security needs may not be a viable alternative.
The alternative solution of running Docker using sibling containers (aka Docker-out-of-Docker or DooD) does not require a privileged container, but has a few drawbacks that stem from the fact that you are launching the container from within a context that is different from that one in which it's running (i.e., you launch the container from within a container, yet it's running at the host's level, not inside the container).
I wrote a blog describing the pros/cons of DinD vs DooD here.
Having said this, Nestybox (a startup I just founded) is working on a solution that runs true Docker-in-Docker securely (without using privileged containers). You can check it out at www.nestybox.com.
I think it will help you to understand the basic differences between Inline-Elements (e.g. span) and Block-Elements (e.g. div), in order to understand why "display: inline-block" is so useful.
Problem: inline elements (e.g. span, a, button, input etc.) take "margin" only horizontally (margin-left and margin-right) on, not vertically. Vertical spacing works only on block elements (or if "display:block" is set)
Solution: Only through "display: inline-block" will also take the vertical distance (top and bottom). Reason: Inline element Span, behaves now like a block element to the outside, but like an inline element inside
Here Code Examples:
/* Inlineelement */
div,
span {
margin: 30px;
}
span {
outline: firebrick dotted medium;
background-color: antiquewhite;
}
span.mitDisplayBlock {
background: #a2a2a2;
display: block;
width: 200px;
height: 200px;
}
span.beispielMargin {
margin: 20px;
}
span.beispielMarginDisplayInlineBlock {
display: inline-block;
}
span.beispielMarginDisplayInline {
display: inline;
}
span.beispielMarginDisplayBlock {
display: block;
}
/* Blockelement */
div {
outline: orange dotted medium;
background-color: deepskyblue;
}
.paddingDiv {
padding: 20px;
background-color: blanchedalmond;
}
.marginDivWrapper {
background-color: aliceblue;
}
.marginDiv {
margin: 20px;
background-color: blanchedalmond;
}
</style>
<style>
/* Nur für das w3school Bild */
#w3_DIV_1 {
bottom: 0px;
box-sizing: border-box;
height: 391px;
left: 0px;
position: relative;
right: 0px;
text-size-adjust: 100%;
top: 0px;
width: 913.984px;
perspective-origin: 456.984px 195.5px;
transform-origin: 456.984px 195.5px;
background: rgb(241, 241, 241) none repeat scroll 0% 0% / auto padding-box border-box;
border: 2px dashed rgb(187, 187, 187);
font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
padding: 45px;
transition: all 0.25s ease-in-out 0s;
}
/*#w3_DIV_1*/
#w3_DIV_1:before {
bottom: 349.047px;
box-sizing: border-box;
content: '"Margin"';
display: block;
height: 31px;
left: 0px;
position: absolute;
right: 0px;
text-align: center;
text-size-adjust: 100%;
top: 6.95312px;
width: 909.984px;
perspective-origin: 454.984px 15.5px;
transform-origin: 454.984px 15.5px;
font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
}
/*#w3_DIV_1:before*/
#w3_DIV_2 {
bottom: 0px;
box-sizing: border-box;
color: black;
height: 297px;
left: 0px;
position: relative;
right: 0px;
text-decoration: none solid rgb(255, 255, 255);
text-size-adjust: 100%;
top: 0px;
width: 819.984px;
column-rule-color: rgb(255, 255, 255);
perspective-origin: 409.984px 148.5px;
transform-origin: 409.984px 148.5px;
caret-color: rgb(255, 255, 255);
background: rgb(76, 175, 80) none repeat scroll 0% 0% / auto padding-box border-box;
border: 0px none rgb(255, 255, 255);
font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
outline: rgb(255, 255, 255) none 0px;
padding: 45px;
}
/*#w3_DIV_2*/
#w3_DIV_2:before {
bottom: 258.578px;
box-sizing: border-box;
content: '"Border"';
display: block;
height: 31px;
left: 0px;
position: absolute;
right: 0px;
text-align: center;
text-size-adjust: 100%;
top: 7.42188px;
width: 819.984px;
perspective-origin: 409.984px 15.5px;
transform-origin: 409.984px 15.5px;
font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
}
/*#w3_DIV_2:before*/
#w3_DIV_3 {
bottom: 0px;
box-sizing: border-box;
height: 207px;
left: 0px;
position: relative;
right: 0px;
text-size-adjust: 100%;
top: 0px;
width: 729.984px;
perspective-origin: 364.984px 103.5px;
transform-origin: 364.984px 103.5px;
background: rgb(241, 241, 241) none repeat scroll 0% 0% / auto padding-box border-box;
font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
padding: 45px;
}
/*#w3_DIV_3*/
#w3_DIV_3:before {
bottom: 168.344px;
box-sizing: border-box;
content: '"Padding"';
display: block;
height: 31px;
left: 3.64062px;
position: absolute;
right: -3.64062px;
text-align: center;
text-size-adjust: 100%;
top: 7.65625px;
width: 729.984px;
perspective-origin: 364.984px 15.5px;
transform-origin: 364.984px 15.5px;
font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
}
/*#w3_DIV_3:before*/
#w3_DIV_4 {
bottom: 0px;
box-sizing: border-box;
height: 117px;
left: 0px;
position: relative;
right: 0px;
text-size-adjust: 100%;
top: 0px;
width: 639.984px;
perspective-origin: 319.984px 58.5px;
transform-origin: 319.984px 58.5px;
background: rgb(191, 201, 101) none repeat scroll 0% 0% / auto padding-box border-box;
border: 2px dashed rgb(187, 187, 187);
font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
padding: 20px;
}
/*#w3_DIV_4*/
#w3_DIV_4:before {
box-sizing: border-box;
content: '"Content"';
display: block;
height: 73px;
text-align: center;
text-size-adjust: 100%;
width: 595.984px;
perspective-origin: 297.984px 36.5px;
transform-origin: 297.984px 36.5px;
font: normal normal 400 normal 21px / 73.5px Lato, sans-serif;
}
/*#w3_DIV_4:before*/
_x000D_
<h1> The Box model - content, padding, border, margin</h1>
<h2> Inline element - span</h2>
<span>Info: A span element can not have height and width (not without "display: block"), which means it takes the fixed inline size </span>
<span class="beispielMargin">
<b>Problem:</b> inline elements (eg span, a, button, input etc.) take "margin" only vertically (margin-left and margin-right)
on, not horizontal. Vertical spacing works only on block elements (or if display: block is set) </span>
<span class="beispielMarginDisplayInlineBlock">
<b>Solution</b> Only through
<b> "display: inline-block" </ b> will also take the vertical distance (top and bottom). Reason: Inline element Span,
behaves now like a block element to the outside, but like an inline element inside</span>
<span class="beispielMarginDisplayInline">Example: here "display: inline". See the margin with Inspector!</span>
<span class="beispielMarginDisplayBlock">Example: here "display: block". See the margin with Inspector!</span>
<span class="beispielMarginDisplayInlineBlock">Example: here "display: inline-block". See the margin with Inspector! </span>
<span class="mitDisplayBlock">Only with the "Display" -property and "block" -Value in addition, a width and height can be assigned. "span" is then like
a "div" block element. </span>
<h2>Inline-Element - Div</h2>
<div> A div automatically takes "display: block." </ div>
<div class = "paddingDiv"> Padding is for padding </ div>
<div class="marginDivWrapper">
Wrapper encapsulates the example "marginDiv" to clarify the "margin" (distance from inner element "marginDiv" to the text)
of the outer element "marginDivWrapper". Here 20px;)
<div class = "marginDiv"> margin is for the margins </ div>
And there, too, 20px;
</div>
<h2>w3school sample image </h2>
source:
<a href="https://www.w3schools.com/css/css_boxmodel.asp">CSS Box Model</a>
<div id="w3_DIV_1">
<div id="w3_DIV_2">
<div id="w3_DIV_3">
<div id="w3_DIV_4">
</div>
</div>
</div>
</div>
_x000D_
The advice isn't that you should never use True
, False
, or None
. It's just that you shouldn't use if x == True
.
if x == True
is silly because ==
is just a binary operator! It has a return value of either True
or False
, depending on whether its arguments are equal or not. And if condition
will proceed if condition
is true. So when you write if x == True
Python is going to first evaluate x == True
, which will become True
if x
was True
and False
otherwise, and then proceed if the result of that is true. But if you're expecting x
to be either True
or False
, why not just use if x
directly!
Likewise, x == False
can usually be replaced by not x
.
There are some circumstances where you might want to use x == True
. This is because an if
statement condition is "evaluated in Boolean context" to see if it is "truthy" rather than testing exactly against True
. For example, non-empty strings, lists, and dictionaries are all considered truthy by an if statement, as well as non-zero numeric values, but none of those are equal to True
. So if you want to test whether an arbitrary value is exactly the value True
, not just whether it is truthy, when you would use if x == True
. But I almost never see a use for that. It's so rare that if you do ever need to write that, it's worth adding a comment so future developers (including possibly yourself) don't just assume the == True
is superfluous and remove it.
Using x is True
instead is actually worse. You should never use is
with basic built-in immutable types like Booleans (True
, False
), numbers, and strings. The reason is that for these types we care about values, not identity. ==
tests that values are the same for these types, while is
always tests identities.
Testing identities rather than values is bad because an implementation could theoretically construct new Boolean values rather than go find existing ones, leading to you having two True
values that have the same value, but they are stored in different places in memory and have different identities. In practice I'm pretty sure True
and False
are always reused by the Python interpreter so this won't happen, but that's really an implementation detail. This issue trips people up all the time with strings, because short strings and literal strings that appear directly in the program source are recycled by Python so 'foo' is 'foo'
always returns True
. But it's easy to construct the same string 2 different ways and have Python give them different identities. Observe the following:
>>> stars1 = ''.join('*' for _ in xrange(100))
>>> stars2 = '*' * 100
>>> stars1 is stars2
False
>>> stars1 == stars2
True
EDIT: So it turns out that Python's equality on Booleans is a little unexpected (at least to me):
>>> True is 1
False
>>> True == 1
True
>>> True == 2
False
>>> False is 0
False
>>> False == 0
True
>>> False == 0.0
True
The rationale for this, as explained in the notes when bools were introduced in Python 2.3.5, is that the old behaviour of using integers 1 and 0 to represent True and False was good, but we just wanted more descriptive names for numbers we intended to represent truth values.
One way to achieve that would have been to simply have True = 1
and False = 0
in the builtins; then 1 and True really would be indistinguishable (including by is
). But that would also mean a function returning True
would show 1
in the interactive interpreter, so what's been done instead is to create bool
as a subtype of int
. The only thing that's different about bool
is str
and repr
; bool
instances still have the same data as int
instances, and still compare equality the same way, so True == 1
.
So it's wrong to use x is True
when x
might have been set by some code that expects that "True is just another way to spell 1", because there are lots of ways to construct values that are equal to True
but do not have the same identity as it:
>>> a = 1L
>>> b = 1L
>>> c = 1
>>> d = 1.0
>>> a == True, b == True, c == True, d == True
(True, True, True, True)
>>> a is b, a is c, a is d, c is d
(False, False, False, False)
And it's wrong to use x == True
when x
could be an arbitrary Python value and you only want to know whether it is the Boolean value True
. The only certainty we have is that just using x
is best when you just want to test "truthiness". Thankfully that is usually all that is required, at least in the code I write!
A more sure way would be x == True and type(x) is bool
. But that's getting pretty verbose for a pretty obscure case. It also doesn't look very Pythonic by doing explicit type checking... but that really is what you're doing when you're trying to test precisely True
rather than truthy; the duck typing way would be to accept truthy values and allow any user-defined class to declare itself to be truthy.
If you're dealing with this extremely precise notion of truth where you not only don't consider non-empty collections to be true but also don't consider 1 to be true, then just using x is True
is probably okay, because presumably then you know that x
didn't come from code that considers 1 to be true. I don't think there's any pure-python way to come up with another True
that lives at a different memory address (although you could probably do it from C), so this shouldn't ever break despite being theoretically the "wrong" thing to do.
And I used to think Booleans were simple!
End Edit
In the case of None
, however, the idiom is to use if x is None
. In many circumstances you can use if not x
, because None
is a "falsey" value to an if
statement. But it's best to only do this if you're wanting to treat all falsey values (zero-valued numeric types, empty collections, and None
) the same way. If you are dealing with a value that is either some possible other value or None
to indicate "no value" (such as when a function returns None
on failure), then it's much better to use if x is None
so that you don't accidentally assume the function failed when it just happened to return an empty list, or the number 0.
My arguments for using ==
rather than is
for immutable value types would suggest that you should use if x == None
rather than if x is None
. However, in the case of None
Python does explicitly guarantee that there is exactly one None
in the entire universe, and normal idiomatic Python code uses is
.
Regarding whether to return None
or raise an exception, it depends on the context.
For something like your get_attr
example I would expect it to raise an exception, because I'm going to be calling it like do_something_with(get_attr(file))
. The normal expectation of the callers is that they'll get the attribute value, and having them get None
and assume that was the attribute value is a much worse danger than forgetting to handle the exception when you can actually continue if the attribute can't be found. Plus, returning None
to indicate failure means that None
is not a valid value for the attribute. This can be a problem in some cases.
For an imaginary function like see_if_matching_file_exists
, that we provide a pattern to and it checks several places to see if there's a match, it could return a match if it finds one or None
if it doesn't. But alternatively it could return a list of matches; then no match is just the empty list (which is also "falsey"; this is one of those situations where I'd just use if x
to see if I got anything back).
So when choosing between exceptions and None
to indicate failure, you have to decide whether None
is an expected non-failure value, and then look at the expectations of code calling the function. If the "normal" expectation is that there will be a valid value returned, and only occasionally will a caller be able to work fine whether or not a valid value is returned, then you should use exceptions to indicate failure. If it will be quite common for there to be no valid value, so callers will be expecting to handle both possibilities, then you can use None
.
The simplest way would be to directly subtract the date objects from one another.
For example:
var hours = Math.abs(date1 - date2) / 36e5;
The subtraction returns the difference between the two dates in milliseconds. 36e5
is the scientific notation for 60*60*1000
, dividing by which converts the milliseconds difference into hours.
From php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
I have tried something like this and it works as expected:
f = open("c:\\log.log", 'r+b')
f.write("\x5F\x9D\x3E")
f.read(100)
f.close()
Where:
f.read(size) - To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string.
And:
f.write(string) writes the contents of string to the file, returning None.
Also if you open Python tutorial about reading and writing files you will find that:
'r+' opens the file for both reading and writing.
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.
You could do this simply by:
NOTE: you can find the right GApp version here:
I've observed this with STS and Eclipse and running java from CMD too on Windows 7/8/10 and following was my simple solution:
Actually, when I installed JDK 8 and STS/Eclipse it created one directory i.e. C:\ProgramData\Oracle\Java\javapath
with the following files:
Along with that, it appended Path Environment variable of System with this location C:\ProgramData\Oracle\Java\javapath
I've just removed above entry from Path Environment variable of System and added the location of the actual JDK instead i.e. C:\Program Files\Java\jdk1.8.0_131\bin
Now that is not necessary to add that -vm option in eclipse.ini or SpringToolSuite4.ini either.
I've gotten around this with
mystr = ' '.join(
["Why, hello there",
"wonderful stackoverflow people!"])
in the past. It's not perfect, but it works nicely for very long strings that need to not have line breaks in them.
See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:
If you want to set the xticklabels:
ax.set_xticks([1,4,5])
ax.set_xticklabels([1,4,5], fontsize=12)
If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):
ax.tick_params(axis="x", labelsize=12)
To do it all at once:
plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold",
horizontalalignment="left")`
Here's my take if you want to try using multiprocesses to process each row of numpy array,
from multiprocessing import Pool
import numpy as np
def my_function(x):
pass # do something and return something
if __name__ == '__main__':
X = np.arange(6).reshape((3,2))
pool = Pool(processes = 4)
results = pool.map(my_function, map(lambda x: x, X))
pool.close()
pool.join()
pool.map take in a function and an iterable.
I used 'map' function to create an iterator over each rows of the array.
Maybe there's a better to create the iterable though.
static String toCamelCase(String s){
String[] parts = s.split(" ");
String camelCaseString = "";
for (String part : parts){
if(part!=null && part.trim().length()>0)
camelCaseString = camelCaseString + toProperCase(part);
else
camelCaseString=camelCaseString+part+" ";
}
return camelCaseString;
}
static String toProperCase(String s) {
String temp=s.trim();
String spaces="";
if(temp.length()!=s.length())
{
int startCharIndex=s.charAt(temp.indexOf(0));
spaces=s.substring(0,startCharIndex);
}
temp=temp.substring(0, 1).toUpperCase() +
spaces+temp.substring(1).toLowerCase()+" ";
return temp;
}
public static void main(String[] args) {
String string="HI tHiS is SomE Statement";
System.out.println(toCamelCase(string));
}
What you're after is the ID3 module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following:
from ID3 import *
try:
id3info = ID3('file.mp3')
print id3info
# Change the tags
id3info['TITLE'] = "Green Eggs and Ham"
id3info['ARTIST'] = "Dr. Seuss"
for k, v in id3info.items():
print k, ":", v
except InvalidTagError, message:
print "Invalid ID3 tag:", message
I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.
Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.
After this, Windows started prioritize Ethernet adapter.
Here a solution with less line of code and easily understandable (or at least I like to think so).
If you want to keep order (match only if the smaller list is found in the same order on the bigger list):
def is_ordered_subset(l1, l2):
# First check to see if all element of l1 are in l2 (without checking order)
if not set(l1).issubset(l2):
return False
length = len(l1)
# Make sublist of same size than l1
list_of_sublist = [l2[i:i+length] for i, x in enumerate(l2)]
#Check if one of this sublist is l1
return l1 in list_of_sublist
In your mysql command line do the following:
mysql> SHOW GLOBAL VARIABLES LIKE '%timestamp%';
+---------------------------------+-------+
| Variable_name | Value |
+---------------------------------+-------+
| explicit_defaults_for_timestamp | OFF |
| log_timestamps | UTC |
+---------------------------------+-------+
2 rows in set (0.01 sec)
mysql> SET GLOBAL explicit_defaults_for_timestamp = 1;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW GLOBAL VARIABLES LIKE '%timestamp%';
+---------------------------------+-------+
| Variable_name | Value |
+---------------------------------+-------+
| explicit_defaults_for_timestamp | ON |
| log_timestamps | UTC |
+---------------------------------+-------+
2 rows in set (0.00 sec)
The compiler needs to know the size of the second dimension in your two dimensional array. For example:
void print_graph(g_node graph_node[], double weight[][5], int nodes);
a simple solution is to use the -ls option in find:
find . -name \*.ear -ls
That gives you each entry in the normal "ls -l" format. Or, to get the specific output you seem to be looking for, this:
find . -name \*.ear -printf "%p\t%k KB\n"
Which will give you the filename followed by the size in KB.
EXPECTED for 302: redirect uses same request method POST on NEW_URL
CLIENT POST OLD_URL -> SERVER 302 NEW_URL -> CLIENT POST NEW_URL
ACTUAL for 302, 303: redirect changes request method from POST to GET on NEW_URL
CLIENT POST OLD_URL -> SERVER 302 NEW_URL -> CLIENT GET NEW_URL (redirect uses GET)
CLIENT POST OLD_URL -> SERVER 303 NEW_URL -> CLIENT GET NEW_URL (redirect uses GET)
ACTUAL for 307: redirect uses same request method POST on NEW_URL
CLIENT POST OLD_URL -> SERVER 307 NEW_URL -> CLIENT POST NEW_URL
You may note that request.json or request.get_json() works only when the "Content-type: application/json" has been added in the header of the request. If you are unable to change the client request configuration, so you can get the body as json like this:
data = json.loads(request.data)
In "pure" bash you have many tools for (sub)string manipulation, mainly, but not exclusively in parameter expansion :
${parameter//substring/replacement}
${parameter##remove_matching_prefix}
${parameter%%remove_matching_suffix}
Indexed substring expansion (special behaviours with negative offsets, and, in newer Bashes, negative lengths):
${parameter:offset}
${parameter:offset:length}
${parameter:offset:length}
And of course, the much useful expansions that operate on whether the parameter is null:
${parameter:+use this if param is NOT null}
${parameter:-use this if param is null}
${parameter:=use this and assign to param if param is null}
${parameter:?show this error if param is null}
They have more tweakable behaviours than those listed, and as I said, there are other ways to manipulate strings (a common one being $(command substitution)
combined with sed or any other external filter). But, they are so easily found by typing man bash
that I don't feel it merits to further extend this post.
Care and feeding of Eclipse's memory hunger is a pain...
More or less, keep trying smaller amounts til it works, that's your max.
Function ListRowCount(ByVal FirstCellName as String) as Long
With thisworkbook.Names(FirstCellName).RefersToRange
If isempty(.Offset(1,0).value) Then
ListRowCount = 1
Else
ListRowCount = .End(xlDown).row - .row + 1
End If
End With
End Function
But if you are damn sure there's nothing around the list, then just thisworkbook.Names(FirstCellName).RefersToRange.CurrentRegion.rows.count
Simple example from https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html
public class Deadlock {
public static void printMessage(String message) {
System.out.println(String.format("%s %s ", Thread.currentThread().getName(), message));
}
private static class Friend {
private String name;
public Friend(String name) {
this.name = name;
}
public void bow(Friend friend) {
printMessage("Acquiring lock on " + this.name);
synchronized(this) {
printMessage("Acquired lock on " + this.name);
printMessage(name + " bows " + friend.name);
friend.bowBack(this);
}
}
public void bowBack(Friend friend) {
printMessage("Acquiring lock on " + this.name);
synchronized (this) {
printMessage("Acquired lock on " + this.name);
printMessage(friend.name + " bows back");
}
}
}
public static void main(String[] args) throws InterruptedException {
Friend one = new Friend("one");
Friend two = new Friend("two");
new Thread(new Runnable() {
@Override
public void run() {
one.bow(two);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
two.bow(one);
}
}).start();
}
}
Output:
Thread-0 Acquiring lock on one
Thread-1 Acquiring lock on two
Thread-0 Acquired lock on one
Thread-1 Acquired lock on two
Thread-1 two bows one
Thread-0 one bows two
Thread-1 Acquiring lock on one
Thread-0 Acquiring lock on two
Thread Dump:
2016-03-14 12:20:09
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.74-b02 mixed mode):
"DestroyJavaVM" #13 prio=5 os_prio=0 tid=0x00007f472400a000 nid=0x3783 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Thread-1" #12 prio=5 os_prio=0 tid=0x00007f472420d800 nid=0x37a3 waiting for monitor entry [0x00007f46e89a5000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.anantha.algorithms.ThreadJoin$Friend.bowBack(ThreadJoin.java:102)
- waiting to lock <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
at com.anantha.algorithms.ThreadJoin$Friend.bow(ThreadJoin.java:92)
- locked <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
at com.anantha.algorithms.ThreadJoin$2.run(ThreadJoin.java:141)
at java.lang.Thread.run(Thread.java:745)
"Thread-0" #11 prio=5 os_prio=0 tid=0x00007f472420b800 nid=0x37a2 waiting for monitor entry [0x00007f46e8aa6000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.anantha.algorithms.ThreadJoin$Friend.bowBack(ThreadJoin.java:102)
- waiting to lock <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
at com.anantha.algorithms.ThreadJoin$Friend.bow(ThreadJoin.java:92)
- locked <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
at com.anantha.algorithms.ThreadJoin$1.run(ThreadJoin.java:134)
at java.lang.Thread.run(Thread.java:745)
"Monitor Ctrl-Break" #10 daemon prio=5 os_prio=0 tid=0x00007f4724211000 nid=0x37a1 runnable [0x00007f46e8def000]
java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:170)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
- locked <0x000000076d20afb8> (a java.io.InputStreamReader)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
- locked <0x000000076d20afb8> (a java.io.InputStreamReader)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at com.intellij.rt.execution.application.AppMain$1.run(AppMain.java:93)
at java.lang.Thread.run(Thread.java:745)
"Service Thread" #9 daemon prio=9 os_prio=0 tid=0x00007f47240c9800 nid=0x3794 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C1 CompilerThread3" #8 daemon prio=9 os_prio=0 tid=0x00007f47240c6800 nid=0x3793 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread2" #7 daemon prio=9 os_prio=0 tid=0x00007f47240c4000 nid=0x3792 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread1" #6 daemon prio=9 os_prio=0 tid=0x00007f47240c2800 nid=0x3791 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread0" #5 daemon prio=9 os_prio=0 tid=0x00007f47240bf800 nid=0x3790 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00007f47240be000 nid=0x378f waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00007f472408c000 nid=0x378e in Object.wait() [0x00007f46e98c5000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x000000076cf88ee0> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
- locked <0x000000076cf88ee0> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)
"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007f4724087800 nid=0x378d in Object.wait() [0x00007f46e99c6000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x000000076cf86b50> (a java.lang.ref.Reference$Lock)
at java.lang.Object.wait(Object.java:502)
at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
- locked <0x000000076cf86b50> (a java.lang.ref.Reference$Lock)
at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)
"VM Thread" os_prio=0 tid=0x00007f4724080000 nid=0x378c runnable
"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f472401f000 nid=0x3784 runnable
"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f4724021000 nid=0x3785 runnable
"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007f4724022800 nid=0x3786 runnable
"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00007f4724024800 nid=0x3787 runnable
"GC task thread#4 (ParallelGC)" os_prio=0 tid=0x00007f4724026000 nid=0x3788 runnable
"GC task thread#5 (ParallelGC)" os_prio=0 tid=0x00007f4724028000 nid=0x3789 runnable
"GC task thread#6 (ParallelGC)" os_prio=0 tid=0x00007f4724029800 nid=0x378a runnable
"GC task thread#7 (ParallelGC)" os_prio=0 tid=0x00007f472402b800 nid=0x378b runnable
"VM Periodic Task Thread" os_prio=0 tid=0x00007f47240cc800 nid=0x3795 waiting on condition
JNI global references: 16
Found one Java-level deadlock:
=============================
"Thread-1":
waiting to lock monitor 0x00007f46dc003f08 (object 0x000000076d0583a0, a com.anantha.algorithms.ThreadJoin$Friend),
which is held by "Thread-0"
"Thread-0":
waiting to lock monitor 0x00007f46dc006008 (object 0x000000076d0583e0, a com.anantha.algorithms.ThreadJoin$Friend),
which is held by "Thread-1"
Java stack information for the threads listed above:
===================================================
"Thread-1":
at com.anantha.algorithms.ThreadJoin$Friend.bowBack(ThreadJoin.java:102)
- waiting to lock <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
at com.anantha.algorithms.ThreadJoin$Friend.bow(ThreadJoin.java:92)
- locked <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
at com.anantha.algorithms.ThreadJoin$2.run(ThreadJoin.java:141)
at java.lang.Thread.run(Thread.java:745)
"Thread-0":
at com.anantha.algorithms.ThreadJoin$Friend.bowBack(ThreadJoin.java:102)
- waiting to lock <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
at com.anantha.algorithms.ThreadJoin$Friend.bow(ThreadJoin.java:92)
- locked <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
at com.anantha.algorithms.ThreadJoin$1.run(ThreadJoin.java:134)
at java.lang.Thread.run(Thread.java:745)
Found 1 deadlock.
Heap
PSYoungGen total 74752K, used 9032K [0x000000076cf80000, 0x0000000772280000, 0x00000007c0000000)
eden space 64512K, 14% used [0x000000076cf80000,0x000000076d8520e8,0x0000000770e80000)
from space 10240K, 0% used [0x0000000771880000,0x0000000771880000,0x0000000772280000)
to space 10240K, 0% used [0x0000000770e80000,0x0000000770e80000,0x0000000771880000)
ParOldGen total 171008K, used 0K [0x00000006c6e00000, 0x00000006d1500000, 0x000000076cf80000)
object space 171008K, 0% used [0x00000006c6e00000,0x00000006c6e00000,0x00000006d1500000)
Metaspace used 3183K, capacity 4500K, committed 4864K, reserved 1056768K
class space used 352K, capacity 388K, committed 512K, reserved 1048576K
BUILD_ID
used to provide this information but they changed it to provide the Build Number since Jenkins 1.597. Refer this for more information.
You can achieve this using the Build Time Stamp plugin as pointed out in the other answers.
However, if you are not allowed or not willing to use a plugin, follow the below method:
def BUILD_TIMESTAMP = null
withCredentials([usernamePassword(credentialsId: 'JenkinsCredentials', passwordVariable: 'JENKINS_PASSWORD', usernameVariable: 'JENKINS_USERNAME')]) {
sh(script: "curl https://${JENKINS_USERNAME}:${JENKINS_PASSWORD}@<JENKINS_URL>/job/<JOB_NAME>/lastBuild/buildTimestamp", returnStdout: true).trim();
}
println BUILD_TIMESTAMP
This might seem a bit of overkill but manages to get the job done.
The credentials for accessing your Jenkins should be added and the id needs to be passed in the withCredentials
statement, in place of 'JenkinsCredentials'
. Feel free to omit that step if your Jenkins doesn't use authentication.
A stack pointer is a small register that stores the address of the top of stack. It is used for the purpose of pointing address of the top of the stack.
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
I just first increased the
"index.number_of_replicas"
by 1 (wait until nodes are synced) then decreased it by 1 afterwards, which effectively removes the unassigned shards and cluster is Green again without the risk of losing any data.
I believe there are better ways but this is easier for me.
Hope this helps.
Try this version which does not require order to be the same but does support having multiple of the same value. They match only if each has the same quantity of any value.
public boolean arraysMatch(List<String> elements1, List<String> elements2) {
// Optional quick test since size must match
if (elements1.size() != elements2.size()) {
return false;
}
List<String> work = newArrayList(elements2);
for (String element : elements1) {
if (!work.remove(element)) {
return false;
}
}
return work.isEmpty();
}
var checked = []
$("input[name='options[]']:checked").each(function ()
{
checked.push(parseInt($(this).val()));
});
If you want to export HTML to PDF. You have many options. without node even
Option 1: Have a button on your html page that calls window.print() function. use the browsers native html to pdf. use media queries to make your html page look good on a pdf. and you also have the print before and after events that you can use to make changes to your page before print.
Option 2. htmltocanvas or rasterizeHTML. convert your html to canvas , then call toDataURL() on the canvas object to get the image . and use a JavaScript library like jsPDF to add that image to a PDF file. Disadvantage of this approach is that the pdf doesnt become editable. If you want data extracted from PDF, there is different ways for that.
Option 3. @Jozzhard answer
You can do:
SELECT lower(FIRST NAME) ABC
FROM PERSON
NOTE: ABC
is used if you want to change the name of the column
[Custom ListView with CheckBox]
If customlayout use checkbox, you must set checkbox focusable = false
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/rowTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
<CheckBox android:id="@+id/CheckBox01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="6sp"
android:focusable="false"> // <---important
</CheckBox>
</RelativeLayout>
Readmore : A ListView with Checkboxes (Without Using ListActivity)
If you have XCode 8.1 and iOS 10.2, update XCode manually to 8.2.1. For some reason App Store didn't offer this update.
I had the similar issue using Flurl.Http:
Flurl.Http.FlurlHttpException: Call failed. Cannot send a content-body with this verb-type. GET http://******:8301/api/v1/agents/**** ---> System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
The problem was I used .WithHeader("Content-Type", "application/json")
when creating IFlurlRequest.
Just thought I'd add that you can do this in Chrome as well:
Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).
You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).
For example:
Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.
Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2
It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.
AnonymousAndrew has also pointed out monitorEvents(window);
here
So, what's wrong with checking each element iteratively?
function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}
$postfields["message"] = "This is a sample ticket opened by the API\rwith a carriage return";
There are two solutions for this issue.
First, is to create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.
Second, if you started to get this error just recently, after MySQL/MariaDB upgrade, like I did, and in case you already have large project with a lot to fix, all you need to do is to edit MySQL/MariaDB configuration file (for example /etc/my.cnf
) and disable strict mode for tables:
[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION
This error started to happen quite recently, due to new strict mode enabled by default. Removing STRICT_TRANS_TABLES
from sql_mode
configuration key, makes it work as before.
You can try this way:
$datetime = new DateTime('2010-12-30 23:21:46');
echo $datetime->format(DATE_ATOM);
I have made a variant solution based on paxdiablo's post
Place the following code in Waitlink.cmd
@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
:loop
set state=up
ping -n 1 !ipaddr! >nul: 2>nul:
if not !errorlevel!==0 set state=down
echo.Link is !state!
if "!state!"=="up" (
goto :endloop
)
ping -n 6 127.0.0.1 >nul: 2>nul:
goto :loop
:endloop
endlocal
For example use it from another batch file like this
call Waitlink someurl.com
net use o: \\someurl.com\myshare
The call to waitlink will only return when a ping was succesful. Thanks to paxdiablo and Gabe. Hope this helps someone else.
Use dict.setdefault()
:
>>> d = {1: 'one'}
>>> d.setdefault(1, '1')
'one'
>>> d # d has not changed because the key already existed
{1: 'one'}
>>> d.setdefault(2, 'two')
'two'
>>> d
{1: 'one', 2: 'two'}
It says already we are running the services with port no 4200 please use another port instead of 4200. Below command is to solve the problem
ng serve --port 4300
Try Using this- Spring 4.0. Working
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
With Swift 3 and Swift 4, String
has a method called data(using:allowLossyConversion:)
. data(using:allowLossyConversion:)
has the following declaration:
func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
Returns a Data containing a representation of the String encoded using a given encoding.
With Swift 4, String
's data(using:allowLossyConversion:)
can be used in conjunction with JSONDecoder
's decode(_:from:)
in order to deserialize a JSON string into a dictionary.
Furthermore, with Swift 3 and Swift 4, String
's data(using:allowLossyConversion:)
can also be used in conjunction with JSONSerialization
's json?Object(with:?options:?)
in order to deserialize a JSON string into a dictionary.
With Swift 4, JSONDecoder
has a method called decode(_:from:)
. decode(_:from:)
has the following declaration:
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
Decodes a top-level value of the given type from the given JSON representation.
The Playground code below shows how to use data(using:allowLossyConversion:)
and decode(_:from:)
in order to get a Dictionary
from a JSON formatted String
:
let jsonString = """
{"password" : "1234", "user" : "andreas"}
"""
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let decoder = JSONDecoder()
let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
} catch {
// Handle error
print(error)
}
}
With Swift 3 and Swift 4, JSONSerialization
has a method called json?Object(with:?options:?)
. json?Object(with:?options:?)
has the following declaration:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
Returns a Foundation object from given JSON data.
The Playground code below shows how to use data(using:allowLossyConversion:)
and json?Object(with:?options:?)
in order to get a Dictionary
from a JSON formatted String
:
import Foundation
let jsonString = "{\"password\" : \"1234\", \"user\" : \"andreas\"}"
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
} catch {
// Handle error
print(error)
}
}
This can be achieved as follows:
this.itemArr = this.itemArr.filter( h => h.id !== ID);
Open:
Start Menu
-> Programs
-> Microsoft Visual Studio 2010
-> Visual Studio Tools
-> Visual Studio Command Prompt (2010)
Run in command prompt:
aspnet_regiis -i
Make sure it is run at administrator, check that the title starts with Administrator
:
Here is my batch script that I put together based on the good answers here & in other posts
You can set title timeout & even sleep to schedule it for latter & \n for new line
Name it popup.bat & put it in your windows path folder to work globally on your pc
For example popup Line 1\nLine 2
will produce a 2 line popup box
(type popup /?
for usage)
Here is the code
<!-- : Begin CMD
@echo off
cscript //nologo "%~f0?.wsf" %*
set pop.key=[%errorlevel%]
if %pop.key% == [-1] set pop.key=TimedOut
if %pop.key% == [1] set pop.key=Ok
if %pop.key% == [2] set pop.key=Cancel
if %pop.key% == [3] set pop.key=Abort
if %pop.key% == [4] set pop.key=Retry
if %pop.key% == [5] set pop.key=Ignore
if %pop.key% == [6] set pop.key=Yes
if %pop.key% == [7] set pop.key=No
if %pop.key% == [10] set pop.key=TryAgain
if %pop.key% == [11] set pop.key=Continue
if %pop.key% == [99] set pop.key=NoWait
exit /b
-- End CMD -->
<job><script language="VBScript">
'on error resume next
q =""""
qsq =""" """
Set objArgs = WScript.Arguments
Set objShell= WScript.CreateObject("WScript.Shell")
Popup = 0
Title = "Popup"
Timeout = 0
Mode = 0
Message = ""
Sleep = 0
button = 0
If objArgs.Count = 0 Then
Usage()
ElseIf objArgs(0) = "/?" or Lcase(objArgs(0)) = "-h" or Lcase(objArgs(0)) = "--help" Then
Usage()
End If
noWait = Not wait()
For Each arg in objArgs
If (Mid(arg,1,1) = "/") and (InStr(arg,":") <> 0) Then haveSwitch = True
Next
If not haveSwitch Then
Message=joinParam("woq")
Else
For i = 0 To objArgs.Count-1
If IsSwitch(objArgs(i)) Then
S=split(objArgs(i) , ":" , 2)
select case Lcase(S(0))
case "/m","/message"
Message=S(1)
case "/tt","/title"
Title=S(1)
case "/s","/sleep"
If IsNumeric(S(1)) Then Sleep=S(1)*1000
case "/t","/time"
If IsNumeric(S(1)) Then Timeout=S(1)
case "/b","/button"
select case S(1)
case "oc", "1"
button=1
case "ari","2"
button=2
case "ync","3"
button=3
case "yn", "4"
button=4
case "rc", "5"
button=5
case "ctc","6"
button=6
case Else
button=0
end select
case "/i","/icon"
select case S(1)
case "s","x","stop","16"
Mode=16
case "?","q","question","32"
Mode=32
case "!","w","warning","exclamation","48"
Mode=48
case "i","information","info","64"
Mode=64
case Else
Mode=0
end select
end select
End If
Next
End If
Message = Replace(Message,"/\n", "°" )
Message = Replace(Message,"\n",vbCrLf)
Message = Replace(Message, "°" , "\n")
If noWait Then button=0
Wscript.Sleep(sleep)
Popup = objShell.Popup(Message, Timeout, Title, button + Mode + vbSystemModal)
Wscript.Quit Popup
Function IsSwitch(Val)
IsSwitch = False
If Mid(Val,1,1) = "/" Then
For ii = 3 To 9
If Mid(Val,ii,1) = ":" Then IsSwitch = True
Next
End If
End Function
Function joinParam(quotes)
ReDim ArgArr(objArgs.Count-1)
For i = 0 To objArgs.Count-1
If quotes = "wq" Then
ArgArr(i) = q & objArgs(i) & q
Else
ArgArr(i) = objArgs(i)
End If
Next
joinParam = Join(ArgArr)
End Function
Function wait()
wait=True
If objArgs.Named.Exists("NewProcess") Then
wait=False
Exit Function
ElseIf objArgs.Named.Exists("NW") or objArgs.Named.Exists("NoWait") Then
objShell.Exec q & WScript.FullName & qsq & WScript.ScriptFullName & q & " /NewProcess: " & joinParam("wq")
WScript.Quit 99
End If
End Function
Function Usage()
Wscript.Echo _
vbCrLf&"Usage:" _
&vbCrLf&" popup followed by your message. Example: ""popup First line\nescaped /\n\nSecond line"" " _
&vbCrLf&" To triger a new line use ""\n"" within the msg string [to escape enter ""/"" before ""\n""]" _
&vbCrLf&"" _
&vbCrLf&"Advanced user" _
&vbCrLf&" If any Switch is used then you must use the /m: switch for the message " _
&vbCrLf&" No space allowed between the switch & the value " _
&vbCrLf&" The switches are NOT case sensitive " _
&vbCrLf&"" _
&vbCrLf&" popup [/m:""*""] [/t:*] [/tt:*] [/s:*] [/nw] [/i:*]" _
&vbCrLf&"" _
&vbCrLf&" Switch | value |Description" _
&vbCrLf&" -----------------------------------------------------------------------" _
&vbCrLf&" /m: /message:| ""1 2"" |if the message have spaces you need to quote it " _
&vbCrLf&" | |" _
&vbCrLf&" /t: /time: | nn |Duration of the popup for n seconds " _
&vbCrLf&" | |<Default> untill key pressed" _
&vbCrLf&" | |" _
&vbCrLf&" /tt: /title: | ""A B"" |if the title have spaces you need to quote it " _
&vbCrLf&" | | <Default> Popup" _
&vbCrLf&" | |" _
&vbCrLf&" /s: /sleep: | nn |schedule the popup after n seconds " _
&vbCrLf&" | |" _
&vbCrLf&" /nw /NoWait | |Continue script without the user pressing ok - " _
&vbCrLf&" | | botton option will be defaulted to OK button " _
&vbCrLf&" | |" _
&vbCrLf&" /i: /icon: | ?/q |[question mark]" _
&vbCrLf&" | !/w |[exclamation (warning) mark]" _
&vbCrLf&" | i/info|[information mark]" _
&vbCrLf&" | x/stop|[stop\error mark]" _
&vbCrLf&" | n/none|<Default>" _
&vbCrLf&" | |" _
&vbCrLf&" /b: /button: | o |[OK button] <Default>" _
&vbCrLf&" | oc |[OK and Cancel buttons]" _
&vbCrLf&" | ari |[Abort, Retry, and Ignore buttons]" _
&vbCrLf&" | ync |[Yes, No, and Cancel buttons]" _
&vbCrLf&" | yn |[Yes and No buttons]" _
&vbCrLf&" | rc |[Retry and Cancel buttons]" _
&vbCrLf&" | ctc |[Cancel and Try Again and Continue buttons]" _
&vbCrLf&" ---> | ---> |The output will be saved in variable ""pop.key""" _
&vbCrLf&"" _
&vbCrLf&"Example:" _
&vbCrLf&" popup /tt:""My MessageBox"" /t:5 /m:""Line 1\nLine 2\n/\n\nLine 4""" _
&vbCrLf&"" _
&vbCrLf&" v1.9 By RDR @ 2020"
Wscript.Quit
End Function
</script></job>
svn log --verbose -r 42
Just in case someone is looking for user Display Name as opposed to User Name, like me.
Here's the treat :
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName.
Add Reference to System.DirectoryServices.AccountManagement
in your project.
Can you use unix commands? I think using head -1
and tail -n 1
are probably the most efficient methods. Alternatively, you could use a simple fid.readline()
to get the first line and fid.readlines()[-1]
, but that may take too much memory.
The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.
On other servers, where the same services are consumed, the certificates were configured as follows:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"
As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"
Once that change was made, all was well. Thanks to everyone who offered assistance.
super()
returns a parent-like object in new-style classes:
class A(object):
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
super(B, self).__init__()
B()
Using Android Studio
you have to add the dependency of the support library that was not indicated in the tutorial
dependencies {
implementation 'com.android.support:appcompat-v7:22.0.0'
}
Other have hit this one on the head:
main(int argc, char **argv)
give you direct access to the command line (after it has been mangled and tokenized by the shell)getopt()
and getopt_long()
but as you've seen the code to use them is a bit wordy, and quite idomatic. I generally push it out of view with something like:
typedef
struct options_struct {
int some_flag;
int other_flage;
char *use_file;
} opt_t;
/* Parses the command line and fills the options structure,
* returns non-zero on error */
int parse_options(opt_t *opts, int argc, char **argv);
Then first thing in main:
int main(int argc, char **argv){
opt_t opts;
if (parse_options(&opts,argc,argv)){
...
}
...
}
Or you could use one of the solutions suggested in Argument-parsing helpers for C/UNIX.
RegexBuddy is telling me if you want to include it at the beginning, this is the correct syntax:
"(?i)\\b(\\w+)\\b(\\s+\\1)+\\b"
The solution posted by https://stackoverflow.com/users/1373278/hoss above worked for me. I am reproducing it here because I cannot yet comment on hoss' post:
Remove import android.R;
from your activity file in question.
My setup:
Android Studio 1.2.2
Exported project from one Mac to Git (everything was working). I then imported the project on another Mac from Git. Thats when it stopped resolving the resource files.
I tried everything on this thread:
Nothing worked except removing import android.R;
from my activity java file.
To avoid this issue in the future add .idea
folder to your .gitignore
file. There is a nice plugin from git for gitignore in Android Studio. Install this plugin and right click in .idea > Add to .gitignore
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
You hide Bootstrap modals with:
$('#modal').modal('hide');
Saying $().hide()
makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.
Perhaps a 63.2% / 36.8% is a reasonable choice. The reason would be that if you had a total sample size n and wanted to randomly sample with replacement (a.k.a. re-sample, as in the statistical bootstrap) n cases out of the initial n, the probability of an individual case being selected in the re-sample would be approximately 0.632, provided that n is not too small, as explained here: https://stats.stackexchange.com/a/88993/16263
For a sample of n=250, the probability of an individual case being selected for a re-sample to 4 digits is 0.6329. For a sample of n=20000, the probability is 0.6321.
There is a danger with using the <input type="text" pattern="\d*">
to bring up the numeric keyboard. On firefox and chrome, the regular expression contained within the pattern causes the browser to validate the input to that expression. errors will occur if it doesn't match the pattern or is left blank. Be aware of unintended actions in other browsers.
code bit should read:
var my_json;
$.getJSON(my_url, function(json) {
my_json = json;
});
I had saw a lot of good solutions, but I'd like to give a what I think as more complete and user-friendly solution, which include:
1, Limit length.
2, If input more, give a callback to trigger your toast.
3, Cursor can be at middle or tail.
4, User can input by paste a string.
5, Always discard overflow input and keep origin.
public class LimitTextWatcher implements TextWatcher {
public interface IF_callback{
void callback(int left);
}
public IF_callback if_callback;
EditText editText;
int maxLength;
int cursorPositionLast;
String textLast;
boolean bypass;
public LimitTextWatcher(EditText editText, int maxLength, IF_callback if_callback) {
this.editText = editText;
this.maxLength = maxLength;
this.if_callback = if_callback;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (bypass) {
bypass = false;
} else {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(s);
textLast = stringBuilder.toString();
this.cursorPositionLast = editText.getSelectionStart();
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.toString().length() > maxLength) {
int left = maxLength - s.toString().length();
bypass = true;
s.clear();
bypass = true;
s.append(textLast);
editText.setSelection(this.cursorPositionLast);
if (if_callback != null) {
if_callback.callback(left);
}
}
}
}
edit_text.addTextChangedListener(new LimitTextWatcher(edit_text, MAX_LENGTH, new LimitTextWatcher.IF_callback() {
@Override
public void callback(int left) {
if(left <= 0) {
Toast.makeText(MainActivity.this, "input is full", Toast.LENGTH_SHORT).show();
}
}
}));
What I failed to do is, if user highlight a part of the current input and try to paste an very long string, I don't know how to restore the highlight.
Such as, max length is set to 10, user inputed '12345678', and mark '345' as highlight, and try to paste a string of '0000' which will exceed limitation.
When I try to use edit_text.setSelection(start=2, end=4) to restore origin status, the result is, it just insert 2 space as '12 345 678', not the origin highlight. I'd like someone solve that.
This is a solution with no deprecated class or method : (Java 8 approved)
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
Important information : Using NoopHostnameVerifier is a security risk
You need install Queuelib
either via the Python Package Index (PyPI)
or from source.
To install using pip:-
$ pip install queuelib
To install using easy_install:-
$ easy_install queuelib
If you have downloaded a source tarball you can install it by running the following (as root):-
python setup.py install
Note: starting with git 1.9/2.0 (Q1 2014), git fetch --tags
fetches tags in addition to what are fetched by the same command line without the option.
See commit c5a84e9 by Michael Haggerty (mhagger):
Previously, fetch's "
--tags
" option was considered equivalent to specifying the refspecrefs/tags/*:refs/tags/*
on the command line; in particular, it caused the
remote.<name>.refspec
configuration to be ignored.But it is not very useful to fetch tags without also fetching other references, whereas it is quite useful to be able to fetch tags in addition to other references.
So change the semantics of this option to do the latter.If a user wants to fetch only tags, then it is still possible to specifying an explicit refspec:
git fetch <remote> 'refs/tags/*:refs/tags/*'
Please note that the documentation prior to 1.8.0.3 was ambiguous about this aspect of "
fetch --tags
" behavior.
Commit f0cb2f1 (2012-12-14)fetch --tags
made the documentation match the old behavior.
This commit changes the documentation to match the new behavior (seeDocumentation/fetch-options.txt
).Request that all tags be fetched from the remote in addition to whatever else is being fetched.
Since Git 2.5 (Q2 2015) git pull --tags
is more robust:
See commit 19d122b by Paul Tan (pyokagan
), 13 May 2015.
(Merged by Junio C Hamano -- gitster
-- in commit cc77b99, 22 May 2015)
pull
: remove--tags
error in no merge candidates caseSince 441ed41 ("
git pull --tags
": error out with a better message., 2007-12-28, Git 1.5.4+),git pull --tags
would print a different error message ifgit-fetch
did not return any merge candidates:It doesn't make sense to pull all tags; you probably meant: git fetch --tags
This is because at that time,
git-fetch --tags
would override any configured refspecs, and thus there would be no merge candidates. The error message was thus introduced to prevent confusion.However, since c5a84e9 (
fetch --tags
: fetch tags in addition to other stuff, 2013-10-30, Git 1.9.0+),git fetch --tags
would fetch tags in addition to any configured refspecs.
Hence, if any no merge candidates situation occurs, it is not because--tags
was set. As such, this special error message is now irrelevant.To prevent confusion, remove this error message.
With Git 2.11+ (Q4 2016) git fetch
is quicker.
See commit 5827a03 (13 Oct 2016) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 9fcd144, 26 Oct 2016)
fetch
: use "quick"has_sha1_file
for tag followingWhen fetching from a remote that has many tags that are irrelevant to branches we are following, we used to waste way too many cycles when checking if the object pointed at by a tag (that we are not going to fetch!) exists in our repository too carefully.
This patch teaches fetch to use HAS_SHA1_QUICK to sacrifice accuracy for speed, in cases where we might be racy with a simultaneous repack.
Here are results from the included perf script, which sets up a situation similar to the one described above:
Test HEAD^ HEAD
----------------------------------------------------------
5550.4: fetch 11.21(10.42+0.78) 0.08(0.04+0.02) -99.3%
That applies only for a situation where:
- You have a lot of packs on the client side to make
reprepare_packed_git()
expensive (the most expensive part is finding duplicates in an unsorted list, which is currently quadratic).- You need a large number of tag refs on the server side that are candidates for auto-following (i.e., that the client doesn't have). Each one triggers a re-read of the pack directory.
- Under normal circumstances, the client would auto-follow those tags and after one large fetch, (2) would no longer be true.
But if those tags point to history which is disconnected from what the client otherwise fetches, then it will never auto-follow, and those candidates will impact it on every fetch.
Git 2.21 (Feb. 2019) seems to have introduced a regression when the config remote.origin.fetch
is not the default one ('+refs/heads/*:refs/remotes/origin/*'
)
fatal: multiple updates for ref 'refs/tags/v1.0.0' not allowed
Git 2.24 (Q4 2019) adds another optimization.
See commit b7e2d8b (15 Sep 2019) by Masaya Suzuki (draftcode
).
(Merged by Junio C Hamano -- gitster
-- in commit 1d8b0df, 07 Oct 2019)
fetch
: useoidset
to keep the want OIDs for faster lookupDuring
git fetch
, the client checks if the advertised tags' OIDs are already in the fetch request's want OID set.
This check is done in a linear scan.
For a repository that has a lot of refs, repeating this scan takes 15+ minutes.In order to speed this up, create a
oid_set
for other refs' OIDs.
In Linux systems, you can use file command. It will give the correct encoding
Sample:
file blah.csv
Output:
blah.csv: ISO-8859 text, with very long lines
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>teste4</groupId>
<artifactId>teste4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bootstrap</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
</dependencies>
</project>
DateTime.Now.Date.ToShortDateString()
is culture specific.
It is best to stick with:
DateTime.Now.ToString("d/MM/yyyy");
Use <packages xmlns="urn:packages">
in the place of <packages>
In order to execute a spool file in plsql Go to File->New->command window -> paste your code-> execute. Got to the directory and u will find the file.
The crc code in zlib (http://zlib.net/) is among the fastest there is, and has a very liberal open source license.
And you should not use adler-32 except for special applications where speed is more important than error detection performance.
if you want fillter only small alphabet letter between square bracket a-z
(\[[a-z]*\])
if you want small and caps letter a-zA-Z
(\[[a-zA-Z]*\])
if you want small caps and number letter a-zA-Z0-9
(\[[a-zA-Z0-9]*\])
if you want everything between square bracket
if you want text , number and symbols
(\[.*\])
Bart Kiers, your regex has a couple issues. The best way to do that is this:
(.*[a-z].*) // For lower cases
(.*[A-Z].*) // For upper cases
(.*\d.*) // For digits
In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.
For the sake of documentation. I spent two days working out an ajax problem and this afternoon when I started testing, my PHP ajax handler wasn't getting called....
Extraordinarily frustrating.
The solution to my problem (which might help others) is the priority of the add_action.
add_action ('wp_ajax_(my handler), array('class_name', 'static_function'), 1);
recalling that the default priority = 10
I was getting a return code of zero and none of my code was being called.
...noting that this wasn't a WordPress problem, I probably misspoke on this question. My apologies.
Sometimes it is possible to have most of implementation hidden in cpp file, if you can extract common functionality foo all template parameters into non-template class (possibly type-unsafe). Then header will contain redirection calls to that class. Similar approach is used, when fighting with "template bloat" problem.
Best File Upload Using Jquery Ajax With Materialise Click Here to Download
When you select image the image will be Converted in base 64 and you can store this in to database so it will be light weight also.
This works better for me:
Simple:
ApplicationController.helpers.my_helper_method
Advance:
class HelperProxy < ActionView::Base
include ApplicationController.master_helper_module
def current_user
#let helpers act like we're a guest
nil
end
def self.instance
@instance ||= new
end
end
Source: http://makandracards.com/makandra/1307-how-to-use-helper-methods-inside-a-model