id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23537700
|
i want to know if there is something wrong with the code and why when i open it as an EXE it takes so long to open.
resetting the password for some of ZkTeck fingerprint machine
from tkinter import *
root = Tk()
root.title('ZkTeco Password Reset')
root.config(bg='orange')
def zkteco():
try:
time = int(a.get())
result = 9999 - time
x = result * result
label.config(text=(f"Username: 8888\nPassword: {x}"))
except ValueError:
print("Inter Valid Number")
Label(root, text="Enter the time on the machine screen!",
font=('calibri', 30, 'bold'),
background='orange',
foreground='white').pack()
a = Entry(root, width=36)
a.pack()
label = Label(root, text="",
font=('Arial', 15, 'bold'),
background="black",
width=18,
foreground="white")
label.pack(pady=20)
Button(root, text="Calculate",
background="green",
width=20,
foreground="black",
command=zkteco).pack()
Button(root,
text='Exit',
width=20,
background="green",
foreground="black",
command=root.quit).pack()
root.mainloop()
| |
doc_23537701
|
A: Try to use Fiddler. It has great functionality for capturing all kind of web requests. Also it has the ability to search within a response document
A: If you only need to expose the requests that your browser chrome is managing, you can use a very powerful tool build in Chrome, you can access it from here:
chrome://net-internals/#events
It records DNS, Proxy, Cache, Extensions and all the Events, including URL_REQUEST, opened sockets, ...
| |
doc_23537702
|
Thanks
A: You could have one of a few problems, Clicking on the link in android webview does not get highlighted visually says you have to set Javascript as enabled with:
webView.getSettings().setJavascriptEnabled(true);
There's also been an issue with focus at Android:Webview with link highlight, where you should request focus on your webview with:
webView.requestFocus(View.FOCUS_DOWN);
| |
doc_23537703
|
/posts/notorious-b-i-g-is-the-best
which is suboptimal since Google construes the query "Notorious B.I.G." as "Notorious BIG" instead of "Notorious B I G" (i.e., the dots are removed rather than treated as spaces)
Likewise, "Tom's fave pizza" is converted to "tom-s-fave-pizza", when it should be "toms-fave-pizza" (since Google ignores apostrophe's as well)
To create a better parameterize, I need to know which characters Google removes from queries (so I can remove them from my URLs) and which characters Google treats as spaces (so I can convert them to dashes in my URLs).
Better still, does such a parameterize method exist?
(Besides stringex, which I think tries to be too clever. 2 representative problem cases:
[Dev]> "Notorious B.I.G. is the best".to_url
=> "notorious-b-dot-i-g-is-the-best"
[Dev]> "No, Curren$y is the best".to_url
=> "no-curren$y-is-the-best"
A: I would try using a gem that has been designed for generating slugs. They often make good design decisions and they have a way of updating the code for changing best practices. This document represents Google's best practices on URL design.
Here is a list of the best gems for solving this problem. They are sorted by rank which is computed based on development activity and how many people "watch" changes to the gems source code.
The top one right now is frendly_id and it looks like it will generate good slugs for your use in SEO. Here is a link to the features of the gem. You can also configure it and it looks like it is perfect for your needs.
A: Google appears to have good results for both the "b-i-g" and "big" in the url slugs.
For the rails side of things, yes a parameterize method exists.
"Notorious B.I.G. is the best".parameterize
=> "notorious-b-i-g-is-the-best"
I think you can create the URLs yourself... something like
class Album
before_create :set_permalink
def set_permalink
self.permalink = name.parameterize
end
def to_params
"#{id}-#{permalink}"
end
end
This will create a url structure of:
/albums/3453-notorious-b-i-g-is-the-best
You can remove the id section in to_params if you want to.
A: Use the title tag and description meta tag to tell google what the page is called: these carry more weight than the url. So, leave your url as /posts/notorious-b-i-g-is-the-best but put "Notorious B.I.G. is the best" in your title tag.
| |
doc_23537704
|
I tried to print the Height of the picture. Iam getting
"Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object."
Pfb the Program.cs file:
class Program
{
private static GraphServiceClient _graphClient;
static void Main(string[] args)
{
var config = LoadAppSetting();
if (config == null)
{
Console.Write("Invalid appsettings.json");
return;
}
var client = GetAuthenticatedGraphClient(config);
var graphRequest = client.Users.Request();
var results = graphRequest.GetAsync().Result;
foreach(var user in results)
{
//Console.Write(user.Id + ": " + user.DisplayName);
ProfilePhoto pro = user.Photo;
Console.Write(pro.Height);
/* DataServiceStreamResponse photo = user.ThumbnailPhoto.DownloadAsync();
using (MemoryStream s = new MemoryStream())
{
}*/
}
Console.WriteLine("\nGraph Request:");
Console.WriteLine(graphRequest.GetHttpRequestMessage().RequestUri);
}
private static IConfigurationRoot LoadAppSetting()
{
try
{
var config = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build();
if (String.IsNullOrEmpty(config["applicationId"]) ||
String.IsNullOrEmpty(config["applicationSecret"]) ||
String.IsNullOrEmpty(config["redirectUri"]) ||
String.IsNullOrEmpty(config["tenantId"]))
{
return null;
}
return config;
}
catch(System.IO.FileNotFoundException)
{
return null;
}
}
private static IAuthenticationProvider CreateAuthorizationProvider(IConfigurationRoot config)
{
var clientId = config["applicationId"];
var clientSecret = config["applicationSecret"];
var redirectUri = config["redirectUri"];
var authority = $"https://login.microsoftonline.com/{config["tenantId"]}/v2.0";
List<string> scopes = new List<string>();
scopes.Add("https://graph.microsoft.com/.default");
//var cca = new ConfidentialClientApplication(clientId, authority, redirectUri, new ClientCredential(clientSecret), null, null);
var cca = ConfidentialClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret)
.Build();
return new MsalAuthenticationProvider(cca, scopes.ToArray());
}
private static GraphServiceClient GetAuthenticatedGraphClient(IConfigurationRoot config)
{
var authenticationProvider = CreateAuthorizationProvider(config);
_graphClient = new GraphServiceClient(authenticationProvider);
return _graphClient;
}
}
}
Pfb the screenshot of permission that the user and application hold.
enter image description here
Also Iam able to retrieve the Profile picture via postman but not via Dot net. Pfb the screenshot from postman:
enter image description here
A: looks like for few of the user ,profile photo is not updated (its null), you can check if there is profile is null? I recommend you to check in graph-explore.
| |
doc_23537705
|
I have tried pytesseract but the resultant text is not accurate. I found alphabets in the text rather than latitude and longitude.
I need to get data in the form: Title of the image, Latitude, Longitude
[![Lat_Image][2]][2]
path = 'C:/BackUp/PhD/Data_from_Core_AP/Python/GeoTaggingWellsImages/filtered_images/Chittoor/'+file
img = cv2.imread(path)
crop_img = img[365:385,10:395]
gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(crop_img,245 ,255, cv2.THRESH_TRUNC)
cv2.imwrite("C:/BackUp/PhD/Data_from_Core_AP/Python/GeoTaggingWellsImages/filtered_images/temp.jpeg", gray)
text = pytesseract.image_to_string(Image.open("C:/BackUp/PhD/Data_from_Core_AP/Python/GeoTaggingWellsImages/filtered_images/temp.jpeg"), config='outputbase digits')
[1]: https://i.stack.imgur.com/aoc3I.jpg
[2]: https://i.stack.imgur.com/pMgER.jpg
| |
doc_23537706
|
I have a call back interface for logging declared as follows
public interface ILoggerCallback
{
void critical(ref string message);
void debug(ref string message);
void error(ref string message);
void infohigh(ref string message);
void infolow(ref string message);
void warning(ref string message);
}/**/
C++ COM client implements the interface (class log_cb) and for now prints everything to console.
HRESULT __stdcall log_cb::raw_infohigh(BSTR* message )
{
wprintf(L"\nwarning: %s", *message);
return S_OK;
}
I have created a worker thread in COM Client using boost threads to do the COM initialisation, instance creation etc.
When the following call back is made in the c#com server
log.infohigh("Successfully initialised server");
I have noticed that the log call back fails with this exception on Windows 2008 R2 test machine but works fine on win7 dev machine
C:\TEMP\COMServerTest>SampleCOMClient.exe
Successfully created instance
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at System.StubHelpers.InterfaceMarshaler.ConvertToManaged(IntPtr pUnk, IntPtr itfMT, IntPtr classMT, Int32 flags)
I tried this with windows threading and it works fine.
Mere inclusion of
#include "boost/thread.hpp"
causes this error.
Could anyone explain me what is happening here.
Many thanks.
| |
doc_23537707
|
This is my service class
public class MyService extends Service{
Sensor proxSensor;
SensorManager sm;
public static MyService instance;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
instance = this;
return Service.START_STICKY;
}
public void startScan(){
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
proxSensor=sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
SensorEventListener eventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
Log.e("Sensor","Value "+sensorEvent.values[0]);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
sm.registerListener(eventListener, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
I am starting service from my main activity
public void viewNotification(View view){
startService(new Intent(this,MyService.class));
}
public void viewNotification2(View view){
MyService.instance.startScan();
}
The Log output is printed correctly while the app is running but when I close the activity and remove it from previous apps list the output is not given. But if I call startScan() within onStartCommand it goes on running even after I close the app.
Why doesn't it keep on giving the output?
Is there any other method instead of using static MyService to achieve this?
A: First of all - use service binding or aidl approaches for working with your Service. (see: https://developer.android.com/guide/components/bound-services.html)
For example:
Suppose, we have service named MyService.
In this class you need write next
private final IBinder mBinder = new LocalServiceBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalServiceBinder extends Binder {
public MyService getBinder() {
return MyService.this;
}
}
Next in your Activity:
private MyService mService;
boolean isBounded;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "onServiceConnected");
MyService.LocalServiceBinder binder = (MyService.LocalServiceBinder) service;
mService = binder.getBinder();
isBounded = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "onServiceDisconnected");
isBounded = false;
}
};
And
@Override
protected void onStart() {
super.onStart();
bindService(new Intent(this, MyService.class), mServiceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (isBounded) {
unbindService(mServiceConnection);
isBounded = false;
}
}
Now you can call your service methods like:
private void activityMethod(){
if (isBounded){
mService.someMethod();
}
}
Second, for working in foreground, call startForeground (int id, Notification notification) method.
| |
doc_23537708
|
How do I change it to 24 hours clock? I've found that I need to change alwaysUse24HourFormat property in Window class but i have no idea how to do it.
Could anyone help me?
Thank you in advance for your answers.
edit:
code is shown below:
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay response = await showTimePicker(
context: context,
initialTime: pickedTime,
);
if (response != null && response != pickedTime) {
setState(() {
pickedTime = response;
});
}
}
edit2:
i tried this only with Android.
A: The above answers didn't work for me. Maybe for the new flutter or dart version. I fixed it by -
final newTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
builder: (context, child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child ?? Container(),
);
},
);
A: Before reading this answer, you need to know how MediaQuery.of() works. Essentially, there is a tree of widgets in any given page. The widgets each have a Context which you can think of as a node in the tree. When you call MediaQuery.of(context), it basically traces up the tree until it finds (or doesn't find) a MediaQuery widget, and then returns the data associated with the widget.
What you want to do is possible, but you have to be slightly careful about how you do it. See below for a minimal code example:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) =>
MediaQuery(data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true), child: child),
home: new Container(
color: Colors.white,
child: Center(
child: Builder(
builder: (context) => FlatButton(
onPressed: () => showTimePicker(context: context, initialTime: TimeOfDay.now()),
child: Text("Show Time Picker"),
),
),
),
),
);
}
}
There are a couple of things of note here. First is that I'm creating a new MediaQueryData from the old one in the builder for MaterialApp. This is because you can't modify the properites of a MaterialQueryData.
The second is that I'm wrapping the child in the builder for MaterialApp with a new MediaQuery. This is necessary so that all 'pages' in the navigator (which is part of material app in this instance) read this new MediaQueryData with MediaQuery.of().
The third is that I use a Builder around the FlatButton. If I didn't do that, the context that it would be using would be the context of MyApp, rather than a context under the MaterialApp. If you made your own class to enclose the 'page', that wouldn't be necessary.
The MediaQuery has to be put where it is now, because if you make it within your 'page' (anywhere under the container), it won't actually be read by the TimePicker widget. This is because the TimePicker is actually inserting itself as the top element of the navigation stack which lives under the Navigator (and MaterialApp), rather than being embedded under your page. If this wasn't the case, it would be much more difficult to use a time picker.
I don't know that I did a very good job of explaining that, so here's a diagram:
MyApp <------ Context (the one that would have been used without the builder)
MaterialApp
MediaQuery (from flutter)
MediaQuery copy (that was made in the builder)
Navigator (implicit - built as part of MaterialApp)
|- Container
| Center
| Builder <----\ Context (used to showTimePicker)
| FlatButton ----/
\- TimePicker
A: Taking in consideration @rmtmckenzie answer, you can actually simplify what he told you. You don't need to set the alwaysUse24HourFormat: true within your MyApp context.
This will do the trick
void inputTimeSelect() async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
builder: (BuildContext context, Widget child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child,
);
},
);
}
And the widget tree can be whatever you want.
A: If someone use flutter_form_builder, here's an example:
FormBuilderDateTimePicker(
name: field.attribute,
inputType: InputType.both,
decoration: InputDecoration(labelText: field.labelText),
alwaysUse24HourFormat: true,
transitionBuilder: (BuildContext context, Widget? child) {
return MediaQuery(
data:
MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child ?? Container(),
);
},
);
| |
doc_23537709
|
BR
Kivu
A: Nothing will happen to data in KeyChain, keychain persists even after the app is removed, it is linked to AppID and the access rights depend on the provisioning profile used when signing your application.
On iPhone, Keychain rights depend on the provisioning profile used to
sign your application. Be sure to consistently use the same
provisioning profile across different versions of your application
A: After my customers upgraded to a new version of my App using KeyChain.... under iOS7 they lost all the information.
| |
doc_23537710
|
const jwt = require("jsonwebtoken");
const sa = require("./credentials-ads.json");
const authUrl = "https://www.googleapis.com/oauth2/v4/token";
const scope = "https://www.googleapis.com/auth/adwords";
const getSignedJwt = () => {
const token = {
iss: sa.client_email,
iat: parseInt(Date.now() / 1000),
exp: parseInt(Date.now() / 1000) + 60 * 60, // 60 minutes
aud: authUrl,
scope,
};
return jwt.sign(token, sa.private_key, { algorithm: "RS256" });
};
const signedJwt = getSignedJwt();
console.log(signedJwt);
const google_token = await axios.post(
'https://oauth2.googleapis.com/token',
'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion='+signedJwt,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
);
res.send(google_token.data);
})
the above giving the access_token as response but it is returned as follows:
{"access_token":"abcdefghijklmnopqurstuvwxyz1234567890qwertyuiopasdfghjklzxcvbnmfasdfasdfasdf........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................","expires_in":3599,"token_type":"Bearer"}
this access token is not usable for any API call
I am trying this using HTTP/HTTPS requests in Nodejs
Was expecting to receive a usable access token, but receiving an incorrect token with .............
A: For domain wide delegation you must supply the subject to delegate as. The value of this is the email address of the user on your domain which you want the service account to impersonate.
you are probably missing sub filed.
A: The multiple dots appended to the access token do not invalidate it for Google APIs and services. Google is testing larger token sizes. Ignore the fact the dots are there as the dots are padding. This allows Google to detect applications that truncate the token size.
For more information:
OAuth 2.0 Access Token Size for Google Cloud Platform Customers
| |
doc_23537711
|
I want to add version v1.1 in between.
How can i do it using cmd's with out manually dropping v2 and running flyway migrate once again?
A: Run with outOfOrder turned on; see the migrate docs.
Option: outOfOrder
Required: No
Default: false
Description: Allows migrations to be run "out of order".
If you already have versions 1 and 3 applied, and now a version 2 is found, it will be applied too instead of being ignored.
If you're running via the command line then do the following:
*
*Add new migration as V1.1__description.sql or similar
*Run flyway again with -outOfOrder true
| |
doc_23537712
|
2019-09-09 17:19:01.083 32714-32738/? I/Unity: AdMob Init() called.
(Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 48)
2019-09-09 17:19:01.231 32714-32738/? I/Ads: Updating ad debug logging enablement.
2019-09-09 17:19:01.245 32714-449/? W/Ads: Update ad debug logging enablement as false
2019-09-09 17:19:01.256 32714-32714/? I/WebViewFactory: Loading com.google.android.webview version 76.0.3809.132 (code 380913235)
2019-09-09 17:19:01.354 32714-32714/? I/cr_LibraryLoader: Time to load native libraries: 1 ms (timestamps 2360-2361)
2019-09-09 17:19:01.372 32714-32714/? I/chromium: [INFO:library_loader_hooks.cc(51)] Chromium logging enabled: level = 0, default verbosity = 0
2019-09-09 17:19:01.372 32714-32714/? I/cr_LibraryLoader: Expected native library version number "76.0.3809.132", actual native library version number "76.0.3809.132"
2019-09-09 17:19:01.396 32714-456/? W/cr_ChildProcLH: Create a new ChildConnectionAllocator with package name = com.google.android.webview, sandboxed = true
2019-09-09 17:19:01.403 32714-32714/? I/cr_BrowserStartup: Initializing chromium process, singleProcess=false
2019-09-09 17:19:01.415 464-464/? E//system/bin/webview_zygote32: Failed to make and chown /acct/uid_99752: Permission denied
2019-09-09 17:19:01.415 464-464/? E/Zygote: createProcessGroup(99752, 0) failed: Permission denied
2019-09-09 17:19:01.436 2987-8127/? I/ActivityManager: Start proc 464:com.google.android.webview:sandboxed_process0/u0i752 for webview_service com.techsanskriti.thearcher/org.chromium.content.app.SandboxedProcessService0
2019-09-09 17:19:01.440 32714-32714/? W/kriti.thearcher: type=1400 audit(0.0:45571): avc: denied { read } for name="vmstat" dev="proc" ino=4026546034 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:proc:s0 tclass=file permissive=0
2019-09-09 17:19:01.468 494-494/? E/asset: setgid: Operation not permitted
Following are the filtered lines having Error:
2019-09-09 17:19:01.415 464-464/? E//system/bin/webview_zygote32: Failed to make and chown /acct/uid_99752: Permission denied
2019-09-09 17:19:01.415 464-464/? E/Zygote: createProcessGroup(99752, 0) failed: Permission denied
2019-09-09 17:19:01.468 494-494/? E/asset: setgid: Operation not permitted
Below is the AndroidManifest.xml generated:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.abc.xyz" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal">
<supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
<application android:theme="@style/UnityThemeSelector" android:icon="@mipmap/app_icon" android:label="@string/app_name">
<activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name" android:screenOrientation="landscape" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density" android:hardwareAccelerated="false">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
<meta-data android:name="android.notch_support" android:value="true" />
<meta-data android:name="android.notch_support" android:value="true" />
<meta-data android:name="android.notch_support" android:value="true" />
</activity>
<meta-data android:name="unity.build-id" android:value="xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />
<meta-data android:name="unity.splash-mode" android:value="0" />
<meta-data android:name="unity.splash-enable" android:value="True" />
<meta-data android:name="notch.config" android:value="portrait|landscape" />
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-xxxxxxxxxxx~xxxxxxxxxxxx" />
</application>
<uses-feature android:glEsVersion="0x00020000" />
<uses-feature android:name="android.hardware.vulkan" android:required="false" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
<uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>
Thanks in advance for any help.
| |
doc_23537713
|
cmd = [ 'dir.exe', u'по-русски' ]
p = subprocess.Popen([ 'dir.exe', u'по-русски' ])
Error log:
Traceback (most recent call last):
File "process.py", line 48, in <module>
cyrillic()
File "process.py", line 45, in cyrillic
p = subprocess.Popen(cmd, shell=True, stdin=None, stdout=None, stderr=subprocess.PIPE)
File "C:\Python\27\Lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python\27\Lib\subprocess.py", line 870, in _execute_child
args = '{} /c "{}"'.format (comspec, args)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-10: ordinal not in range(128)
I tried different executables - 7z.ex, ls.exe - popen fails before even running them.
But what if I encode unicode string to a specific encoding?
# it works because 1251 is kinda native encoding for my Windows
cmd = [ 'dir.exe', CYRILLIC_FILE_NAME.encode('windows-1251') ]
# fails because 1257 cannot be converted to 1251 without errors
cmd = [ 'dir.exe', BALTIC_FILE_NAME.encode('windows-1251') ]
# this may work but it's not a solution because...
cmd = [ 'dir.exe', BALTIC_FILE_NAME.encode('windows-1257') ]
The "bad" thing, I have different file names on my computer - baltic, cyrillic and many more. So it looks there is no general way to pass a non-ASCII file name to Popen on Windows?! Or could that be fixed still? (Without dirty hacks preferably.)
Windows 7, Python 2.7.3
A: If you use Python 3, it will pass the parameters properly as Unicode. Assuming your subprocess can load unicode parameters on the command line (Python 2 cannot), then it should work.
For example, this script, when run under Python 3, will display the Cyrillic characters.
import subprocess
subprocess.call(["powershell", "-c", "echo", "'по-русски'"])
| |
doc_23537714
|
Here is the HTML:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
I have to clone to
<ul>
</ul>
without repeat a li and until to complete 3 elements
Here is my jquery code
var total = $(this).find('.contentSecond ul li').length;
$('first.content ul li').click(function() {
for (var i = 0; i <= total; i++) {
$(this).clone().appendTo($('.contentSecond ul'));
}
return false;
});
What's wrong?
| |
doc_23537715
|
I didn't create the agent pool, but the server administrator has added me as an administrator of the pool - which according to the documentation is the only permission needed to register an agent.
However, when I attempt to register the agent using the command-line tool, I get the following error:
Connecting to the server. Access denied. Harper, Ed needs Manage
permissions for pool to perform the action. For more
information, contact the Azure DevOps Server administrator.
Failed to add the agent. Try again or ctrl-c to quit
The server admin also tried adding me to the build administrators group for the project associated with the agent pool. This had no effect and I got the same error.
What permission/role membership do I need to add agents to the pool?
A: I met the exactly same issue here. And the solution for my case is pretty simple - following the steps Microsoft provides exactly, based on the documentation.
In the permission section of document, it mentions you need to check our permission from Orgnazation settings. It seems like the Orignazation level setting and Project level setting for the same agent pool have separate permission groups. So you could try to do the following from Orgnazation settings.
I didn't create the agent pool, but the server administrator has added me as an administrator of the pool - which according to the documentation is the only permission needed to register an agent.
That's how I solved my problem(intially I only have administrator permission from the Project setting -> agent pool setting and see same error).
A: Not exactly an answer on the permissions needed, but as a member of the project build administrator role, I could create a new agent pool.
I was able to add the agent to the new pool without any problems.
| |
doc_23537716
|
The information in the database looks like this:
x(1),0.1,0.7,0.2
z(0.5),0.2,0.3,0.5
etc...
I want to draw a grid of boxes. The fill in the boxes will be based on the information from the MySQL database.
I understand that I can use PHP to retrieve the information. But how do I go from retrieving the info to drawing a box? I guess what I am asking is how do you bridge the gap from server side to client side when trying to draw things. I found a bunch of code on how to display text but not how to draw boxes with different fills that change on various data.
| |
doc_23537717
|
i have followed the steps for installing open cv and the other dependencies but when i try to run it i get the following error
(cv) pi@raspberrypi:~/Smart-Security-Camera $ python main.py
Traceback (most recent call last):
File "main.py", line 3, in <module>
from mail import sendEmail
File "/home/pi/Smart-Security-Camera/mail.py", line 2, in <module>
from email.MIMEMultipart import MIMEMultipart
ImportError: No module named 'email.MIMEMultipart'
i then tried entering "sudo python main.py" and got a different messege but the same problem as shown below
(cv) pi@raspberrypi:~/Smart-Security-Camera $ sudo python main.py
Traceback (most recent call last):
File "main.py", line 5, in <module>
from camera import VideoCamera
File "/home/pi/Smart-Security-Camera/camera.py", line 2, in <module>
from imutils.video.pivideostream import PiVideoStream
ImportError: No module named imutils.video.pivideostream
finally i tried "sudo python3 main.py" and again different messege same issue.
(cv) pi@raspberrypi:~/Smart-Security-Camera $ sudo python3 main.py
Traceback (most recent call last):
File "main.py", line 1, in <module>
import cv2
ImportError: No module named 'cv2'
any help is appreciated
| |
doc_23537718
|
it's throwing "System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:52747"
Unit test Cs file:
CS file for the get method:
When I run test method , it's keep on refusing
| |
doc_23537719
|
My code:
public class SearchUser extends AppCompatActivity{
private static final String TAG = "SearchUser";
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.btnSearchUser);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SearchUser.this);
View mView = getLayoutInflater().inflate(R.layout.searchpopup, null);
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
});
}
});
dialog.show();
}
});
}
LAYOUT XML FILE:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btnUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/user"
mapbox:layout_constraintBottom_toBottomOf="parent"
mapbox:layout_constraintEnd_toEndOf="@+id/mapView"
mapbox:layout_constraintHorizontal_bias="0.0"
mapbox:layout_constraintStart_toStartOf="parent"
mapbox:layout_constraintTop_toTopOf="@+id/mapView"
mapbox:layout_constraintVertical_bias="0.0" />
<Button
android:id="@+id/btnSearchUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/search_user"
mapbox:layout_constraintBottom_toBottomOf="parent"
mapbox:layout_constraintEnd_toEndOf="@+id/mapView"
mapbox:layout_constraintHorizontal_bias="0.0"
mapbox:layout_constraintStart_toStartOf="parent"
mapbox:layout_constraintTop_toTopOf="@+id/mapView"
mapbox:layout_constraintVertical_bias="0.129" />
<Button
android:id="@+id/logoutButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/log_out"
mapbox:layout_constraintBottom_toBottomOf="parent"
mapbox:layout_constraintEnd_toEndOf="@+id/mapView"
mapbox:layout_constraintHorizontal_bias="1.0"
mapbox:layout_constraintStart_toStartOf="@+id/mapView"
mapbox:layout_constraintTop_toTopOf="parent"
mapbox:layout_constraintVertical_bias="0.0" />
<com.mapbox.mapboxsdk.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:layout_constraintBottom_toBottomOf="parent"
mapbox:layout_constraintEnd_toEndOf="parent"
mapbox:layout_constraintStart_toStartOf="parent"
mapbox:layout_constraintTop_toTopOf="parent"
mapbox:mapbox_cameraTargetLat="-34.6131500"
mapbox:mapbox_cameraTargetLng="-58.3772300"
mapbox:mapbox_cameraZoom="12"
mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10">
</com.mapbox.mapboxsdk.maps.MapView>
<Button
android:id="@+id/startButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginEnd="24dp"
android:layout_marginStart="24dp"
android:enabled="true"
android:text="@string/crear_fiesta"
android:textColor="@color/mapboxGrayLight"
mapbox:layout_constraintBottom_toBottomOf="parent"
mapbox:layout_constraintEnd_toEndOf="parent"
mapbox:layout_constraintStart_toStartOf="parent" />
I have tried putting a toast message inside the onClick method but nothing happens, so I guess it just does not enter there.
Anyone know why? Thanks for any answer :D
A: You're overriding the wrong onCreate(), replace it with:
protected void onCreate(@Nullable Bundle savedInstanceState)
Edit: are you sure that this xml should be inflated in class SearchUser? Do you have a class MainActivity like the xml states?
A: Place the btnSearchUser button below the MapView in XML.
You've also configured MapView with match_parent, which is not applicable to a constraint layout parent. Set the height and width of MapView to 0dp as well.
| |
doc_23537720
|
For example, consider the following list of weighted edges containing 4 nodes and 3 edges:
A B 1
A C 2
C D 3
Then the output adjacency matrix is the following:
0 1 2 0
1 0 0 0
2 0 0 3
0 0 3 0
I am looking to do this in a memory-efficient way—100000 by 100000 adjacency matrix (10**10 values). Note that the matrix is symmetric and all of the diagonal values are 0.
A: You can use a sparse matrix. To make it more accessible, use a dictionary for sparse matrix. Use tuple of adjacent vertices as key to the dictionary.
nodes = ['A','B','C','D']
graph = {('A','B'):1, ('A','C'): 2, ('C','D'): 3}
And to access the nodes we use two nested for loops. For each pair of nodes we can check if an edge is present in O(1) time complexity.
For example:
for i in nodes:
for j in nodes:
if (i,j) in graph:
print(i,j,graph[(i,j)])
else:
print("Edge not present.")
Even if you use characters to denote the nodes, you can use the node list in
This method has same time complexity as the regular matrix method. But the space complexity is reduced extremely. And adding new edges or removing edges from the graph dictionary is very easy.
A: You could use a dictionary of dictionaries and only store the edges once with their weight. Using functions to access the weights will allow you to invert the parameter order as needed to get and set the weight values.
def getWeight(adj,a,b):
return getWeight(adj,b,a) if a>b else adj.get(a,{}).get(b,0)
def setWeight(adj,a,b,w):
if a>b: setWeight(adj,b,a,w)
else: adj.setdefault(a,{})[b] = w
edges = [('A','B',1),('A','C',2),('C','D',3)]
adj = {v:{} for e in edges for v in e[:2]}
for a,b,w in edges:
setWeight(adj,a,b,w)
Output:
print(adj)
{'A': {'B': 1, 'C': 2}, 'B': {}, 'C': {'D': 3}, 'D': {}}
print(getWeight(adj,'B','A')) # 1
print(getWeight(adj,'A','B')) # 1
print(getWeight(adj,'D','A')) # 0
If you have the vertices somewhere in another list, you only need to store the edge weights in the dictionary which will make it slightly more memory efficient:
def getWeight(adj,a,b):
return adj[a,b] if (a,b) in adj else adj.get((b,a),0)
def setWeight(adj,a,b,w):
if (b,a) in adj: adj[b,a] = w
else: adj[a,b] = w
edges = [('A','B',1),('A','C',2),('C','D',3)]
adj = {(a,b):w for a,b,w in edges}
print(adj)
{('A', 'B'): 1, ('A', 'C'): 2, ('C', 'D'): 3}
print(getWeight(adj,'B','A')) # 1
print(getWeight(adj,'A','B')) # 1
print(getWeight(adj,'D','A')) # 0
| |
doc_23537721
|
My working code:
$.getJSON(url, function(json)) {
if(typeof json === 'object' && json.length > 0) {
var nameData = [json[0]['name'],json[1]['name'],json[2]['name'],json[3]['name'],json[4]['name'],json[5]['name']];
var matchedData = [json[0]['data']['Matched'],json[1]['data']['Matched'],json[2]['data']['Matched'],json[3]['data']['Matched'],json[4]['data']['Matched'],json[5]['data']['Matched']];
var bookedData = [json[0]['data']['Booked'],json[1]['data']['Booked'],json[2]['data']['Booked'],json[3]['data']['Booked'],json[4]['data']['Booked'],json[5]['data']['Booked']];
}
var options = {
chart: {
renderTo: 'div',
type: 'column'
},
title: {
text: 'Chart Title',
x: -20
},
xAxis: {
type: 'category',
categories: nameData,
crosshair: true
},
series: [{
name: 'Matched',
data: matchedData
}, {
name: 'Booked',
data: bookedData
}]
}
chart = new Highcharts.Chart(options);
}
This renders the chart correctly. However when there are fewer than the usual 6 items in the array, the TypeError stops things.
I attempted this to count the array items prior to sending to Highcharts:
var nameData = [];
var matchedData = [];
var bookedData = [];
if (typeof json === 'object' && json.length > 0) {
for (var a = 0; a < json.length; a++) {
nameData += [json[a]['name']+","];
matchedData += [json[a]['data']['Matched']+","];
bookedData += [json[a]['data']['Booked']+","];
}
}
This alerts() out the same results as the manually-created array, but nothing renders on the chart. What needs to change?
A: Try mapping over your data. You can set everything really easily using the map function. It's a lot cleaner and simpler as well. You can find a reference for map here.
$.getJSON(url, function(json)) {
if(typeof json === 'object' && json.length > 0) {
var nameData = json.map(obj => obj['name']);
var matchedData = json.map(obj => obj['data']['Matched']);
var bookedData = json.map(obj => obj['data']['Booked']);
}
var options = {
chart: {
renderTo: 'div',
type: 'column'
},
title: {
text: 'Chart Title',
x: -20
},
xAxis: {
type: 'category',
categories: nameData,
crosshair: true
},
series: [{
name: 'Matched',
data: matchedData
}, {
name: 'Booked',
data: bookedData
}]
}
chart = new Highcharts.Chart(options);
}
| |
doc_23537722
|
<script type="text/javascript">
$.ajaxSetup({cache: false});
$(document).ready(function() {
// set up the click event
$('a.groups_loader').on('click', function() {
var toLoad = '<? echo base_url(); ?>user/account_groups/';
$('.groupsajax').fadeOut(100, loadContent);
$('#load').remove();
$('#groupswaiting').append('<div id="load" style="height: 400px;"><div id="loader-arm"><div id="loader-lp"><div id="loader-baLabel"></div></div><div id="loader-reflect"></div></div></div>');
$('#load').fadeOut(1000);
function loadContent() {
$('.groupsajax').load(toLoad, '', function(response, status, xhr) {
if (status == 'error') {
var msg = "Sorry but there was an error: ";
$(".groupsajax").html(msg + xhr.status + " " + xhr.statusText);
}
}).fadeIn(4000, hideLoader());
}
function hideLoader() {
$('#load').fadeOut(2000);
}
return false;
});
});
</script>
I would like to know what's changed and how I can fix this. Thanks
A: In case it helps others... the problem was not in the above script, but was in another similar (ajax) script on the page. In the above script I had updated .live('click', function() to .on('click', function() as .live has been deprecated in later versions of JQ. However, another script on the page had not been updated and still used .live, and that was preventing the above script from working. So rather than trying to trouble shoot one script at a time, make sure you update them all first!
| |
doc_23537723
|
But the send function is not picking any error after connection has been broken for more than 20s. Ideally with keepalive enabled, after 20s (keepalive_interval + keepalive_probes*keepalive_time) E_TIMEDOUT should be added to socket pending errors.
As this answer says,
"Both read(2) and write(2) first retrieve any pending error on the
socket before even attempting to handle any data."
The send should pick E_TIMEDOUT or any socket error when connection is closed by keepalive but it is not happening in below code.
int sockfd = -1;
if ((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
cerr<<"ERROR: Failed to obtain Socket Descriptor!"<<endl;
return -1;
}
//setting keepalive
int optval;
socklen_t optlen = sizeof(optval);
//setting keepalive
optval = 1;
optlen = sizeof(optval);
if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0) {
cerr<<"set keepalive failed"<<endl;
return -1;
}
//setting tcp_keepalive_intvl
optval = 10;
optlen = sizeof(optval);
if(setsockopt(sockfd, SOL_TCP, TCP_KEEPINTVL, &optval, optlen) < 0) {
cerr<<"set tcp_keepalive_interval failed"<<endl;
return -1;
}
//setting tcp_keepalive_time
optval = 1;
optlen = sizeof(optval);
if(setsockopt(sockfd, SOL_TCP, TCP_KEEPIDLE, &optval, optlen) < 0) {
cerr<<"set tcp_keepalive_time failed"<<endl;
return -1;
}
//setting tcp_keepalive_probes
optval = 10;
optlen = sizeof(optval);
if(setsockopt(sockfd, SOL_TCP, TCP_KEEPCNT, &optval, optlen) < 0) {
cerr<<"set tcp_keepalive_probe failed"<<endl;
return -1;
}
struct sockaddr_in remote_addr;
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(#port_no);
remote_addr.sin_addr.s_addr = inet_addr(#ip_addr);
memset(&remote_addr.sin_zero, 0, 8);
if (connect(sockfd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) == -1) {
cerr<<"Connect failed with ERRORNO "<<errno<<endl;
return -1;
} else {
cout<<"TcpClient.cpp connected to server"<<endl;
}
while(1) {
char data[20] = "hi hello";
int ret = -1;
if((ret = send(sockfd, data, 20, 0)) < 0) {
cerr<<"TcpClient.cpp:- failed to send_data, ERROR CODE: "<<errno<<endl;
return -1;
} else if (ret == 0) {
cout<<"send returns 0"<<endl;
} else {
cout<<"data sent"<<endl;
}
sleep(1);
}
getchar();
return 0;
I tested this code on a linux machine with gcc compiler.
Note: I tried the same code with recv and it picked E_TIMEDOUT error neatly.
A: You haven't waited long enough. From http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/usingkeepalive.html:
tcp_keepalive_time
the interval between the last data packet sent (simple ACKs are not considered data) and the first keepalive probe; after the connection is marked to need keepalive, this counter is not used any further
tcp_keepalive_intvl
the interval between subsequential keepalive probes, regardless of what the connection has exchanged in the meantime
tcp_keepalive_probes
the number of unacknowledged probes to send before considering the connection dead and notifying the application layer
So with your values of (10, 10, 10), the keepalives will not start until 10 seconds after the last data was received from the peer. Then 10 probes, each separated by 10 seconds will need to be unacknowledged before the connection is declared dead.
| |
doc_23537724
|
For example, the pure Java edition timetabling system can get a 0Hard/-352Soft score. But the web edition can only get -7Hard/-1108Soft. No matter how long we run the example.
The web edition is hosted in a WildFly 9. The JVM versions we use are both Oracle JVM 1.8; Further, we tried using WildFly 10. And the result is the same.
Can anyone shed some light on it? I want get the same performance in web edition as Java edition.
| |
doc_23537725
|
Before flagging as duplicate: I tried to apply answers in Keep ListView.HeaderTemplate visible/static/sticky in UWP for Xamarin.Forms targeting Android without success.
Short code sample:
<ListView ItemsSource="{Binding MyList}"
HasUnevenRows="True"
SeparatorVisibility="Default"
CachingStrategy="RecycleElement">
<ListView.Header>
<Label HorizontalTextAlignment="Center"
FontAttributes="Bold"
Text="Header Title"/>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding Name}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
A: Here is an alternative approach to this if the list isn't long
<StackLayout>
<Label HorizontalTextAlignment="Center"
FontAttributes="Bold"
Text="Header Title"/>
<StackLayout BindableLayout.ItemsSource="{Binding MyList}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding Name}"/>
<!-- boxview as separator -->
<BoxView HeightRequest="1" Color="Aqua" HorizontalOptions="FillAndExpand"/>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</StackLayout>
A: Try to place the label outside the listview, it will be above the ListView regardless of scrolling:
<Label HorizontalTextAlignment="Center"
FontAttributes="Bold"
Text="Header Title"/>
<ListView ItemsSource="{Binding MyList}"
HasUnevenRows="True"
SeparatorVisibility="Default"
CachingStrategy="RecycleElement"
Margin="0,-5,0,0">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding Name}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
| |
doc_23537726
|
(example)
I've found only star rating systems and one slider that is not similar to the one that I'm looking for. (jquery ui slider)
Anyone knows something like that I'm looking for? Otherwise I'm willing to pay someone for this work.
A: It's not hard to roll your own, you just need a combination of jQuery/AJAX, CSS and the server-side poison of your choice.
Here is an example:
http://www.99points.info/2010/05/ajax-rating-system-create-simple-ajax-rating-system-using-jquery-ajax-and-php/
Essentially you wire up client-side event handlers which do AJAX HTTP POST requests to your server-side handler/web service, which then return back the response.
Now, that example isn't exactly a "slider" but it illustrates how it can be accomplished.
Check out this site for a multitude of AJAX slider examples - you just need to combine the two principles (rating and slider) and you're good to go.
Obviously if you don't like the "look" of it, you can mess with the CSS/hovering effects to suit your needs, but that should get you up and running.
| |
doc_23537727
| ERROR: type should be string, got "https://codepen.io/manu506/project/editor/DQyMvM\n/*************************************************************/\n/* BASIC SETUP */\n/************************************************************/\n\n* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nhtml {\n background-color: #ffffff;\n color: #000000;\n font-family: 'Lato', 'Arial', sans-serif;\n font-weight: 300;\n font-size: 18px;\n text-rendering: optimizeLegibility; \n}\n\n\n\n/*************************************************************/\n/* REUSABLE COMPONENTS */\n/************************************************************/\n\n.row {\n width: 1140px;\n margin: 0 auto;\n}\n\nh1 {\n font-family: 'Merrriweather', serif;\n font-weight: 900;\n font-size: 500%;\n}\n\nh2 {\n font-family: 'Merrriweather', serif;\n font-weight: 400;\n font-size: 200%;\n}\n\nh3 {\n font-family: 'lato', 'arial', sans-serif;\n font-weight: 900;\n font-style: italic;\n}\n\np {\n font-family: 'lato', 'arial', sans-serif;\n font-weight: 400;\n font-size: 130%;\n}\n\n.btn {\n display:inline-block;\n padding: 10px 30px;\n font-weight: 300;\n text-decoration: none;\n border: 1px solid #0f0f0f;\n color: #0f0f0f;\n transition: background-color 0.3s, color 0.3s;\n}\n\n.btn:hover, .btn:active {\n background-color: #0f0f0f;\n color: #ffffff;\n}\n\n.btn:visited {\n background-color: #0f0f0f;\n}\n\n\n/*************************************************************/\n/* Navigation */\n/************************************************************/\n\n\n/* Header Background */\n\nheader {\n background-image:linear-gradient(#000000dc, #000000dc), url(https://image.ibb.co/irJBJz/header.jpg);\n background-size: cover;\n background-position: center;\n height: 100vh;\n background-attachment: fixed;\n}\n\n/* Logo */\n\n.logo {\n font-family: 'Merrriweather', serif;\n font-weight: 400;\n font-size: 250%;\n color: #fff;\n display: inline-block;\n position: absolute;\n left: 2%;\n}\n\n/* Navigation Menu */\n\n.nav-menu {\n float: right;\n list-style: none;\n position: absolute;\n right: 2%;\n top: 0%;\n}\n\n.nav-menu li {\n display: inline-block;\n margin: 30px;\n\n}\n\n.nav-menu li a:link,\n.nav-menu li a:visited {\n color: #fff;\n text-decoration: none;\n padding: 4px;\n border-bottom: 2px solid transparent;\n transition: border-bottom 0.5s;\n}\n\n.nav-menu li a:hover,\n.nav-menu li a:active {\n border-bottom: 2px solid #fff;\n}\n\n/* Header Mid Text Box */\n\n.text-box {\n position: absolute;\n width: 100%;\n color:#fff;\n text-align: center;\n top: 25%;\n}\n\n/******** Section 1 *************/\n\n.section1 {\n margin-top: 8%;\n}\n\n.section1-text {\n margin-top: 25%;\n\n}\n\n.section1-text h2 {\n font-size: 350%;\n}\n\n.section1-text h3 {\n font-size: 145%;\n margin-top: 10px;\n}\n\n.section1-text h3::before {\n display: block;\n height: 2px;\n background-color: #e67e22;\n content: \"\";\n width: 90px;\n margin-top: 5px;\n margin-bottom: 5px;\n}\n\n\n.section1-text p {\n color: #555;\n padding-top: 15px;\n padding-bottom: 35px;\n}\n\n\n/* *********** Section 2 ************ */\n\n.section2 {\n margin-top: 10%;\n width: 100%;\n}\n\n.section2-text {\n width: 33.33%;\n margin-top: 10%;\n}\n\n.section2-text h2 {\n font-size: 350%;\n}\n\n.section2-text h3 {\n font-size: 145%;\n margin-top: 10px;\n}\n\n.section2-text h3::before {\n display: block;\n height: 2px;\n background-color: #e67e22;\n content: \"\";\n width: 90px;\n margin-top: 5px;\n margin-bottom: 5px;\n}\n\n.section2-text p {\n color: #555;\n padding-top: 15px;\n padding-bottom: 35px;\n}\n\n/******** Section 3 *************/\n\n.section3-text {\n display: block;\n margin-top: 18%;\n}\n\n.section3-text h2 {\n font-size: 350%;\n}\n\n.section3-text h3 {\n font-size: 145%;\n margin-top: 10px;\n}\n\n.section3-text h3::before {\n display: block;\n height: 2px;\n background-color: #e67e22;\n content: \"\";\n width: 105px;\n margin-top: 5px;\n margin-bottom: 5px;\n}\n\n.section3-text p {\n color: #555;\n padding-top: 15px;\n padding-bottom: 35px;\n}\n\n\n/******** Section 4 *************/\n\n.section4 {\n margin-top: 8%;\n}\n\n.section4-text {\n margin-top: 18%;\n}\n\n.section4-text h2 {\n font-size: 350%;\n}\n\n.section4-text h3 {\n font-size: 145%;\n margin-top: 10px;\n}\n\n.section4-text h3::before {\n display: block;\n height: 2px;\n background-color: #e67e22;\n content: \"\";\n width: 100px;\n margin-top: 5px;\n margin-bottom: 5px;\n}\n\n.section4-text p {\n color: #555;\n padding-top: 15px;\n padding-bottom: 35px;\n}\n\n\n/******** Section 5 *************/\n\n.section5 {\n width: 100%;\n margin-top: 8%;\n}\n\n.section5-img {\n padding-left: 10%;\n}\n\n.section5-text {\n width: 33.33%;\n margin-top: 14%;\n}\n\n.section5-text h2 {\n font-size: 350%;\n}\n\n.section5-text h3 {\n font-size: 145%;\n margin-top: 10px;\n}\n\n.section5-text h3::before {\n display: block;\n height: 2px;\n background-color: #e67e22;\n content: \"\";\n width: 187px;\n margin-top: 5px;\n margin-bottom: 5px;\n}\n\n.section5-text p {\n color: #555;\n padding-top: 15px;\n padding-bottom: 35px;\n}\n\n/******** Section 6 *************/\n\n.section6 {\n margin-top: 11%;\n text-align: center;\n}\n\n.section6 span {\n display: block;\n font-size: 70%;\n}\n\n.section6 h3 {\n margin: 2%;\n font-size: 200%;\n}\n\n.section6 p {\n display: block;\n padding-top: 25px;\n padding-bottom: 25px;\n}\n\n\n/******** Section 7 *************/\n.section7 {\n margin-top: 8%;\n margin-bottom: 8%;\n width: 100%;\n background-color: #161616;\n text-align: center;\n}\n\n.section7-services {\n margin: 0;\n}\n\n.blur-image1 {\n width: 100%;\n height: 700px;\n background-image: url(\"https://image.ibb.co/m9q2Qe/services.jpg\");\n background-repeat: no-repeat;\n background-size: cover;\n opacity: 0;\n transition: opacity 0.5s;\n}\n\n.blur-image1:hover {\n opacity: 1;\n}\n\n.service-text-box {\n display: inline-block;\n width:35%;\n padding-top: 35px;\n padding-bottom: 35px;\n text-align: center;\n border: 2px solid white;\n background-color: #fff;\n transform: translate(0, -450px);\n}\n\n.section7-work {\n margin: 0;\n}\n\n.blur-image2 {\n width: 100%;\n height: 700px;\n background-image: url(\"https://image.ibb.co/muF2Qe/work.jpg\");\n background-repeat: no-repeat;\n background-size: cover;\n opacity: 0;\n transition: opacity 0.5s;\n}\n\n.blur-image2:hover {\n opacity: 1;\n}\n\n.work-text-box {\n display: inline-block;\n width:35%;\n padding-top: 35px;\n padding-bottom: 35px;\n text-align: center;\n border: 2px solid white;\n background-color: #fff;\n transform: translate(0, -450px);\n}\n\nI used https://www.dtelepathy.com/ as an inspiration for the design. But I am not able to achieve the same result. If you look at css and html, from section 1 to section 7, all images are going out of browser boundary. If I use overflow:hidden property, then my images are being cropped out, which I don't want. Can you please help me out?\nI am using this grid system: http://www.responsivegridsystem.com/\n\nA: Add these properties to img tag\nimg {\n width: 100%;\n height: auto;\n font-size: 0;\n}\n\nIf the width property is set to 100%, the image will be responsive and scale up and down:\n\nA: Use this code:\nThis CSS Style is used to be make width of the scroll bar \"0\"\nSo we can hide the scrollbar without overflow hidden.\n::-webkit-scrollbar { width: 0px;}\n\n"
| |
doc_23537728
|
Below is the Main pages initialize function:
public void initialize() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//below gets the connection specified earlier
conn = DriverManager.getConnection(dbURL);
System.out.println("DB Connection Created!");
String createString = "CREATE TABLE Connections (DETAILS VARCHAR(255) NOT NULL, NAME VARCHAR(255) UNIQUE)";
stmt = conn.createStatement();
stmt.execute(createString);
System.out.println("Connections table created!");
//below is for populating the usernames
String sql2 = "Select NICKNAME FROM Users ORDER BY NICKNAME ASC";
stmt = conn.createStatement();
ResultSet rs2 = stmt.executeQuery(sql2);
usernameList.clear();
while(rs2.next()) {
String name = rs2.getString("NICKNAME");
usernameList.add(name);
System.out.println("User initialize: " + name);
}
System.out.println("Objects: " + usernameList);
sourceUsername.setItems(FXCollections.observableArrayList(usernameList));
cbosUsername.setItems(FXCollections.observableArrayList(usernameList));
tiUsername.setItems(FXCollections.observableArrayList(usernameList));
}
catch(Exception e) {
e.printStackTrace();
}
}
Does anyone have any input on an easy way to solve this?
A: I think the best way would be to put CREATE-Statement to Application-Start-Method:
public class MyApp extends Application {
public void start(Stage stage) {
//perform create statement
}
}
or simply catch all Exceptions on your CREATE-Statement:
try{
String createString = "CREATE TABLE Connections (DETAILS VARCHAR(255) NOT NULL, NAME VARCHAR(255) UNIQUE)";
stmt = conn.createStatement();
stmt.execute(createString);
} catch (Exception e){
}
| |
doc_23537729
|
How can I do this?
A: "Service access rules list" page has a rule that only "ADMIN" roles have permission for WFS-Transaction.
wfs.Transation --> ADMIN
You must delete this rule.
| |
doc_23537730
|
How can i add my script for check if a pseudo already exist in my function SignUp ?
_signUp(String _email, String _password, String _pseudo) async {
try {
//Create Get Firebase Auth User
if (_formKey.currentState.validate()) {
await auth.createUserWithEmailAndPassword(
email: _email, password: _password);
//problem here
users.get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
var pseudoDoc = result.data()['pseudo'];
if (pseudoDoc != _pseudo) {
users.doc(auth.currentUser.uid).set({
'pseudo': _pseudo,
'email': _email,
});
} else {
throw 'Pseudo already exist';
}
});
});
//
}
} on FirebaseAuthException catch (error) {
CoolAlert.show(
context: context,
type: CoolAlertType.error,
text: error.message,
);
}
}
}```
| |
doc_23537731
|
Currently what I am doing is storing the paths of all the files of each directory in an array:
Find.find(dir1) do |path|
if File.file?(path)
directory1_files << path # Add path to an array of file_paths for the 1st directory.
end
end # I repeat the process for the second directory and store their paths in an array called directory2_files.
The problem I am having is that when I try and subtract the two arrays (larger array - small array) to get the remaining files, I get an empty array. Reason I get this is because the full paths are trying to be subtracted instead of just the basenames. Ex: ~/folder1/file.txt != ~/folder2/file.txt
How can I find if a file with the same name is in two folders, and remove it from a list so the only files remaining are the ones not present in both folders?
A: Since you know the paths to both folders (i.e. dir1 and dir2) I'd suggest to to calculate paths relative to them, so that later you could compare relative paths (effectively ignoring the ~/folder1 part of the path). Use dictionaries to map between relative and absolute paths (so that you could remove them).
Something like this:
dir1 = '~/folder1'
directory1_files = {}
Find.find(dir1) do |path|
if File.file?(path)
relative_path = path[dir1.length, path.length]
directory1_files[relative_path] = path
end
end
Then, whenever you have directory1_files and directory2_files, compare their .keys in order to find the differences.
A: Use File.basename(filename). This also works if "filename" is a File object.
| |
doc_23537732
|
struct node
{
int label;
long cost=LONG_MAX;
bool visited=false;
bool operator < (const node &other) const { return cost < other.cost; }
}
set<node> S;
//here i just want to update the cost of a node in my set S
set<node>::iterator it=S.find(vertex);
*it.cost=200;
Does that change the order in the set automatically?
A:
Does that change the order in the set automatically?
Not only does it not change the order of the set, but the operation itself is illegal. Associative container iterators give you a const type for the key - so *it in your example has type node const.
If you think about it, that's the only way to ensure the invariant that the container provides. After all, how could it->cost = 200 possibly update the underlying set? Maybe if C++ had reflection and the iterators dereferenced to some proxy that had overloaded operator= that... yeah that just sounds like a mess.
The current idiomatic way to "update" an element in a set involves erasing it, modifying it, and then re-inserting it. In your case:
auto it = S.find(vertex);
node cur = std::move(*it);
auto next = S.erase(it);
cur.cost = 200;
S.insert(next, cur);
That's admittedly pretty tedious.
There is a proposal (P0083R2) to improve this in the future.
Update for C++17: that proposal has been accepted. Now you want to use extract():
auto node = S.extract(vertex);
node.value().cost = 200;
S.insert(std::move(node));
This will avoid an extra copy of your type and an extra allocation/deallocation.
A: You cannot normally change the existing contents of the set. It's a dirty little secret, but std::set iterators are really const_iterators. Go ahead and try to compile that, you'll get compilation errors.
Of course, there are ways around that, but they will result in undefined behavior.
| |
doc_23537733
|
//Cards.php
public function __construct(array $attributes = []) {
$this->gateway = StripeGateway;
}
protected $fillable = ['user_id', 'card_id', 'customer_id', 'exp_year', 'exp_month', 'funding', 'brand', 'last4'];
public function createNewCardFromCustomer($user_id, $customer)
{
$result = $this->create([
'user_id' => $user_id,
'customer_id' => $customer->id,
'card_id' => $customer['sources']['data'][0]->id,
'exp_year' => $customer['sources']['data'][0]->exp_year,
'exp_month' => $customer['sources']['data'][0]->exp_month,
'funding' => $customer['sources']['data'][0]->funding,
'brand' => $customer['sources']['data'][0]->brand,
'last4' => $customer['sources']['data'][0]->last4
]);
return $result;
}
Even the Model static create method receives the right parameters. And I've taken care of the mass assignment also.
A: I posted this on Laracasts too :)
Anyway, you have to change your constructor to this:
public function __construct(array $attributes = []) {
$this->gateway = StripeGateway;
parent::__construct($attributes);
}
You are overriding the Model's base constructor, which changes its default behavior. Laravel uses the constructor for a lot of things (create method, relationships, etc.).
The base model's constructor function does several things, but one very important part of it is that it accepts an array to fill out its attributes as can be seen here:
public function __construct(array $attributes = [])
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
So, after you set your gateway property, you should call the parent's constructor function and pass the attributes.
| |
doc_23537734
|
For example if i connect to it with the private ip the "nat" respond correctly and all is ok.But if i try to connect to this server through a public ip he respond with:you can't connect to this ftp server through a different ip of the ftp.
with filezilla all is ok.(the connection is active and explicit with ssl.
my code:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("IP");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("user", "passw");
request.EnableSsl = true;
request.UsePassive = false;
private bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
//this to resolve the certified problems.
THANK YOU
UP.
| |
doc_23537735
|
public class GPS_module implements LocationListener {
private Context context;
public GPS_module(Context ctx) {
context = ctx;
manager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
}
.....
public void sendMessage(String str) {
Intent intent = new Intent("logGPS");
intent.putExtra("Message",str);
context.sendBroadcast(intent);
}
}
for receiving messages I use the following source code
public class Fragment_1 extends Fragment{
.......
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.right_panel_1, null);
BroadcastReceiver log = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals("logGPS"))
{
myLog(intent.getStringExtra("Message"));
}
}
};
return myFragmentView ;
}
}
A: You need to do something like:
(This is for Connectivity)
registerReceiver(myReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
You need to register and set an intent filter.
A: Have you registered your receiver? I don't see this in your code.
| |
doc_23537736
|
On my computer the macro run just fine and did what I needed, but on this someone's computer it showed that error that I never saw as a VBA developer of “Can't find Project or Library” on the first line of the sub I wanted to excute.
Does anyone have any suggestions or suggestions?
A: just use this pattern:
Sub Test()
On Error Goto Finish
Dim obj As Object
Set obj = CreateObject("YourLibName")
...code...
Finish:
End Sub
So if you can't create object goto finish.
| |
doc_23537737
|
How can I debug Eclipse to see if something is running in background? Does Eclipse have any console or log so I can see what exactly is being done?
Not to mention, I even restarted the Eclipse but it just works for a few moment and then again reaches high CPU usage. What could be the problem?
*
*Windows 7 64bit
*Eclipse Kepler standard (plugins ADT & CDT)
*Java 7
A: You can try add some memory to eclipse.ini parameter -Xmx512m
It can be useful in some cases but you will need to try it..
Hope that helps
| |
doc_23537738
|
A: Unfortunately, Google Maps Platform terms of service prohibit using an API for real-time navigation.
Have a look at paragraph 3.2.4 Restrictions Against Misusing the Services. It reads:
(d) No Re-Creating Google Products or Features. Customer will not use the Services to create a product or service with features that are substantially similar to or that re-create the features of another Google product or service. Customer’s product or service must contain substantial, independent value and features beyond the Google products or services. For example, Customer will not: (i) re-distribute the Google Maps Core Services or pass them off as if they were Customer’s services; (ii) create a substitute of the Google Maps Core Services, Google Maps, or Google Maps mobile apps, or their features; (iii) use the Google Maps Core Services in a listings or directory service or to create or augment an advertising product; (iv) combine data from the Directions API, Geolocation API, and Maps SDK for Android to create real-time navigation functionality substantially similar to the functionality provided by the Google Maps for Android mobile app.
source: https://cloud.google.com/maps-platform/terms/#3-license
The only way compliant with Terms of Service is opening an Intent with Google Maps app in navigation mode.
I hope this clears up your doubt.
| |
doc_23537739
|
I have a main application and a library module, and I'm using the Facebook SDK in the library module. Here's my top project gradle:
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
And the gradle for my library:
apply plugin: 'com.android.library'
android {
compileSdkVersion 23
buildToolsVersion "22.0.1"
defaultConfig {
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.facebook.android:facebook-android-sdk:4.11.0'
}
Now, when I sync gradle, it does seem to build all of the intermediate stuff like it should. However when I try to do an import statement, the only options I get are:
import com.facebook.*
import com.facebook.R
No other options are available. If I try to do this:
import com.facebook.FacebookSdk
The word FacebookSdk is in red, because it can't find it.
I've been beating on this all morning long. I'm converting an old Eclipse project, but this started out as a brand new Android Studio project (not an import from an old Eclipse project). It seems as if there's another Facebook SDK floating around without any exports in it, but I'll be darned if I can't find it. I've also tried quite a few earlier versions of the Facebook SDK, and they all do the same thing.
Where in the heck am I going wrong here?
A: Answered my own question! Little did I know that you have to have a successful build BEFORE you can add the import statements. I had added compile 'com.facebook.android:facebook-android-sdk:4.11.0' then immediately tried to import com.facebook.FacebookSdk without doing a successful build first.
To be fair, step 6 of the Google quick start does say 'Build your project', but the importance of doing this before adding any SDK code kinda bounced off me.
| |
doc_23537740
|
2018-12-11 15:26:04.877
Into a datetime, where there are no microseconds and all seconds are zero:
2018-12-11 15:26:00
What I have done so far is:
import pandas as pd
import datetime
dfdf=pd.read_excel('datefix.xlsx')
print(df.dtypes)
df.date =pd.to_datetime(df.date, errors='coerce')
print(df.date)
df["date"].datetime.replace(microsecond=0)
But I get the following error
AttributeError: 'Series' object has no attribute 'datetime'
Is there another way to get to the outcome desired?
A: Instead of .replace use .strftime('%Y-%m-%d %H:%M:%S') on the datetime object.
If you have a column of datetime objects, apply the function using df['column'].apply(mapper_function)
df["date"] basically gives your a pandas Series object, not an individual objects in the column.
A: You can use dt.floor as follows:
df['date_fixed']= df['date'].dt.floor(freq='S')
| |
doc_23537741
|
date_of_birth = models.DateField()
class PetSerializer(serializers.ModelSerializer):
class Meta:
model = Pet
fields = "__all__"
Now when i trying to do
curl -X POST -H "Content-Type: application/json" \
-d '{
"date_of_birth":"2021-08-29T00:46:27.103Z"
}' http://localhost:8025/api/dob/
I get
{"date_of_birth":["Date has wrong format. Use one of these formats instead: YYYY-MM-DD."]}
How to manage this because i will get input as 2021-08-29T00:46:27.103Z format only
A: Add input_formats to your date field:
class PetSerializer(serializers.ModelSerializer):
date_of_birth = serializers.DateField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ'])
class Meta:
model = Pet
fields = ('date_of_birth', ...)
Docs in https://www.django-rest-framework.org/api-guide/fields/#datefield
| |
doc_23537742
|
a:8:{s:3:"key";s:19:"field_501743d4baa78";s:5:"label";s:8:"Category";s:4:"name";s:8:"category";s:4:"type";s:8:"checkbox";s:12:"instructions";s:0:"";s:8:"required";s:1:"1";s:7:"choices";a:17:{s:4:"Arts";s:4:"Arts";s:8:"Business";s:8:"Business";s:14:"Communications";s:14:"Communications";s:16:"Criminal Justice";s:16:"Criminal Justice";s:13:"Culinary Arts";s:13:"Culinary Arts";s:9:"Education";s:9:"Education";s:11:"Engineering";s:11:"Engineering";s:11:"Health Care";s:11:"Health Care";s:22:"Information Technology";s:22:"Information Technology";s:13:"International";s:13:"International";s:5:"Legal";s:5:"Legal";s:17:"Political Science";s:17:"Political Science";s:10:"Psychology";s:10:"Psychology";s:8:"Religion";s:8:"Religion";s:7:"Science";s:7:"Science";s:9:"Technical";s:9:"Technical";s:10:"Veterinary";s:10:"Veterinary";}s:8:"order_no";s:1:"3";}
to get a list of all the "categorys" such as Arts, Business, Communications etc etc
Thanks for your help
UPDATE
After running unserialize this is what i get:
array(8) { ["key"]=> string(19) "field_501743d4baa78" ["label"]=> string(8) "Category" ["name"]=> string(8) "category" ["type"]=> string(8) "checkbox" ["instructions"]=> string(0) "" ["required"]=> string(1) "1" ["choices"]=> array(17) { ["Arts"]=> string(4) "Arts" ["Business"]=> string(8) "Business" ["Communications"]=> string(14) "Communications" ["Criminal Justice"]=> string(16) "Criminal Justice" ["Culinary Arts"]=> string(13) "Culinary Arts" ["Education"]=> string(9) "Education" ["Engineering"]=> string(11) "Engineering" ["Health Care"]=> string(11) "Health Care" ["Information Technology"]=> string(22) "Information Technology" ["International"]=> string(13) "International" ["Legal"]=> string(5) "Legal" ["Political Science"]=> string(17) "Political Science" ["Psychology"]=> string(10) "Psychology" ["Religion"]=> string(8) "Religion" ["Science"]=> string(7) "Science" ["Technical"]=> string(9) "Technical" ["Veterinary"]=> string(10) "Veterinary" } ["order_no"]=> string(1) "3" }
however i'm not sure how to loop through and just get the category names - sorry - i'm new to PHP - probably just doing something stupid - thanks for your help
A: That's just a serialized array. Just unserialize it and getting the values is easy:
$array = unserialize(a:8:{s:3:"key";s:19:"field_501743d4baa78";s:5:"label";s:8:"Category";s:4:"name";s:8:"category";s:4:"type";s:8:"checkbox";s:12:"instructions";s:0:"";s:8:"required";s:1:"1";s:7:"choices";a:17:{s:4:"Arts";s:4:"Arts";s:8:"Business";s:8:"Business";s:14:"Communications";s:14:"Communications";s:16:"Criminal Justice";s:16:"Criminal Justice";s:13:"Culinary Arts";s:13:"Culinary Arts";s:9:"Education";s:9:"Education";s:11:"Engineering";s:11:"Engineering";s:11:"Health Care";s:11:"Health Care";s:22:"Information Technology";s:22:"Information Technology";s:13:"International";s:13:"International";s:5:"Legal";s:5:"Legal";s:17:"Political Science";s:17:"Political Science";s:10:"Psychology";s:10:"Psychology";s:8:"Religion";s:8:"Religion";s:7:"Science";s:7:"Science";s:9:"Technical";s:9:"Technical";s:10:"Veterinary";s:10:"Veterinary";}s:8:"order_no";s:1:"3";});
var_dump($array);
A: $sample_arr = unserialize($array); //unserialize here
$sample_arr = $sample_arr['choices']; //get the array
then you have the category list saved to $sample_arr.
foreach($sample_arr as $temp) {
//do stuff with each element here
}
Examples include outputting this as a html list
echo '<ul>';
foreach($sample_arr as $temp) {
echo '<li>' . $temp . '</li>';
}
echo '</ul>';
| |
doc_23537743
|
notifyThread . Both the methods will hold a same lock obj. waitThread in the while loop of synchronized block will call wait method ,the lock of thread1 is released and other thread say thread2 need to go for notifyThread method and set the flag value to true. But the output iam getting is
Both the thread1 and thread2 are entering in waitThread method. None of them are entering the notifyThread method . Can anyone please suggest what is going on here ,why it is not entering the notifyThread method. If it needs to enter notifyThread what can be done?
public class Customer implements Runnable
{
public boolean flag=false;
public Object obj=new Object();
public void run()
{
waitThread();
notifyThread();
}
public void waitThread()
{
synchronized(obj)
{
System.out.println(Thread.currentThred().getName()+"in the waitThread");
while(!flag)
{
System.out.println(Thread.currentThred().getName()+"in the waitThread calling wait");
try
{
obj.wait();
}
catch(Exception e)
{
}
}
}
}
public void notifyThread()
{
synchronized(obj)
{
System.out.println(Thread.currentThred().getName()+"in the notifyThread");
flag=true;
System.out.println(Thread.currentThred().getName()+" notify the previous thread");
obj.notify();
}
}
}
}
Creating two threads
public class Test
{
public static void main(String args[])
{
Customer cus=new Customer();
Thread t1=new Thread(cus);
Thread t2=new Thread(cus);
t1.start();
t2.start();
}
}
A: You are calling waitThread() method first, so both the threads go into the WAIT state and remain there. No one is invoking the notify() method for the threads to come out of the WAIT state.
public void run()
{
waitThread();// HERE, wait is getting called first.
notifyThread(); // control doesn't come here at all.
}
| |
doc_23537744
|
A: Press CTRL+SHIFT+R to refresh intellisense cache
| |
doc_23537745
|
The states are; S1, S2, S3, BEGIN, END
The values are rounded and truncated.
The smoothed State transition table is as follows;
S1 S2 S3 B E
S1 -0.7 -1.6 -1.6 -INF -2.0
S2 -2.0 -1.3 -0.7 -INF -2.0
S3 -1.3 -0.7 -2.0 -INF -2.0
B -1.2 -1.2 -1.2 -INF -1.9
E -INF -INF -INF -INF -INF
The smoothed emission table from states to red, green, blue;
RED GREEN BLUE
S1 -0.9 -1.2 -1.6
S2 -1.6 -0.9 -1.2
S3 -1.6 -1.6 -0.6
B -INF -INF -INF
E -INF -INF -INF
The question is;
Symbols have been seen are;
RED RED GREEN BLUE
what are the most likely states?
Therefore;
I created the Viterbi algorithm matrix according to values above;
First row represent the S1, S2, S3 values when RED symbol seen, just like that rest of rows for S1,S2,S3 values when red, green and blue seen.
For the first row I calculated it;
values are smoothed by taking natural logarithms of them therefore I am adding values instead of multiplying.
For the first red seen;
δ(S1) = MAX{P(S1|B)+P(R|S1)+δ(B)} = -1.2 - 0.9 + 0= -2.1
δ(S2) = MAX{P(S2|B)+P(R|S2)+δ(B)} = -1.2 - 1.6 + 0= -2.8
δ(S3) = MAX{P(S3|B)+P(R|S3)+δ(B)} = -1.2 - 1.6 + 0= -2.8
Just like above, for the next red seen;
δ(S1) = MAX{ (P(S1|S1)+P(R|S1)+δ(S1) ), ( P(S1|S2)+P(R|S2)+δ(S2) ), ( P(S1|S3)+P(R|S3)+δ(S3) )}
= MAX{ (-0.7-0.9-2.1),(-1.6-1.6-2.8), (-1.6-1.6-2.8) } = MAX{-3.7, -6, -6}
The maximum is -3.7 therefore S1 value when RED is seen; -3.7 . Rest of the values are calculated as above.
Viterbi Algorithm Matrix;
S1 S2 S3 B E
RED -2.1 -2.8 -2.8 -INF -INF
RED -3.7 -5.2 -5.2 -INF -INF
GREEN -5.8 -6.3 -7.0 -INF -INF
BLUE -8.1 -8.6 -7.8 -INF -INF
The answer of this example shows that most likely states are; S1, S1, S2, S3
However shouldn't it be; S1, S1, S1, S3? Because maximum value for the first red is -2.1 which is belong S1 and for second red it is again S1, and for the third one again S1 value is highest and for the blue S3 value is the highest. I can be wrong because I actually couldn't understand the dynamic programming approach for Viterbi.
A: You should begin to trust well-established algorithms ;-). Seriously, you made no mistake in the calculation of the first two steps, and as the algorithm proceeds in the same way, I guess you haven't either in the following steps.
So what is going on here? I guess your mistake (imo, it isn't a mistake, but rather it is good that you try to understand things) here is that you are not incoporating the last step into your thoughts. In fact, if you had the state sequence RED,RED,GREEN, your result would be S1,S1,S1.
However, when you now add the next signal, BLUE, the algorithm takes into account that transitions S1->S3 (which is the preferred state for BLUE) are much more unlikely than S2->S3. Thus it favors S1,S1,S2,S3 instead of S1,S1,S1,S3, even though the latter would minimize the first three signals alone.
| |
doc_23537746
|
print 'Listening...'
while not shutdown:
while sys.stdin in select.select([sys.stdin], [], [], 0)[0]: #look for keyboard input... not working
line = sys.stdin.readline()
if line:
send_message(line)
else: # an empty line means stdin has been closed
print('eof')
exit(0)
try: # listen for other peers
clientsock,clientaddr = mySocket.accept()
print 'Incoming connection from', clientaddr
clientsock.settimeout(None)
t = threading.Thread( target = HandlePeer, args = [clientsock] )
t.start()
except KeyboardInterrupt:
print "shutting down"
shutdown = True
continue
except Exception,e:
print 'error in peer connection %s %s' % (Exception,e)
mySocket.close()
HandlePeer checks for incoming messages from the newly connected peer. I just need a way of sending messages.
A: The short answer is you'll need to use curses.
Its a lot more difficult than just calling input() and receiving a response, but it is what you'll need. There is a good resource called Curses Programming with Python which is the best place to start.
| |
doc_23537747
|
import clr
clr.AddReferenceToFileAndPath("C:\\Microsoft\\Exchange\\Web Services\\2.1\\Microsoft.Exchange.WebServices.dll")
from Microsoft.Exchange.WebServices.Data import *
def main():
ex_service = ExchangeService(ExchangeVersion.Exchange2010)
ex_service.UseDefaultCredentials = True
ex_service.AutodiscoverUrl("me@companycom", redirect_url_validation_callback)
email = EmailMessage(ex_service)
email.ToRecipients.Add('r1@company.com')
email.Subject = "New TIP Report"
email.Body = '''A new TIP report has been published.
Please visit https://google.com and login to complete the form.'''
email.Send()
def redirect_url_validation_callback(redirect_url):
redirect_uri = Uri(redirect_url)
return redirect_uri.Scheme == "https"
if __name__ == "__main__":
main()
I read that I need to Mime Content properties, but I was not able to succeed. Any clue how to add multiple recipients using EWS API?
A: Just add a new line
email.ToRecipients.Add('r1@company.com')
| |
doc_23537748
|
My client needs report with records count at bottom of his report.
Something like this:
Select * from My_table where id>5
union all
select ('Record Count: ' + count(*)) from My_table where id>5
| |
doc_23537749
|
What's the correct way of reacting to keyboard input, e.g. the arrow keys, and change TilePos by one whenever a key is pressed once?
A: You probably want to look at the cookbook for more examples.
If there is only one player, then you should make it a resource so that you can just do: ResMut<TilePos> in the function definition.
Otherwise you can do:
#[derive(Default)]
struct State {
event_reader: EventReader<KeyboardInput>,
}
/// This system prints out all keyboard events as they come in
fn print_keyboard_event_system(
mut state: Local<State>,
keyboard_input_events: Res<Events<KeyboardInput>>,
mut query: Query<&mut TilePos>
) {
for event in state.event_reader.iter(&keyboard_input_events) {
if event.state == bevy::input::ElementState::Pressed && event.key_code == Some(bevy::input::keyboard::KeyCode::Up){
for mut t in &mut query.iter_mut() {
t.1 += 1;
println!("New Tile: {} {}", t.0, t.1);
println!("{:?}", event);
}
}
}
}
If you were wanting to edit a specific tile, then you could spawn it with another component (.with()) and make the query more specific with Query<TilePos, With<Specific>>.
This code is adapted from here.
| |
doc_23537750
|
should urllib.urlopen() be followed by urllib.close()? Otherwise, one would leak connections, correct?
A: Strictly speaking, this is true. But in practice, once (if) urllib goes out of scope, the connection will be closed by the automatic garbage collector.
A: Like @Peter says, out-of-scope opened URLs will become eligible for garbage collection.
However, also note that in CPython URLopener defines:
def __del__(self):
self.close()
This means that when the reference count for that instance reaches zero, its __del__ method will be called, and thus its close method will be called as well. The most "normal" way for the reference count to reach zero is to simply let the instance go out of scope, but there's nothing strictly stopping you from an explicit del x early (however it doesn’t directly call __del__ but just decrements the reference count by one).
It's certainly good style to explicitly close your resources -- especially when your application runs the risk of using too much of said resources -- but Python will automatically clean up for you if you don't do anything funny like maintaining (circular?) references to instances that you don't need any more.
A: The close method must be called on the result of urllib.urlopen, not on the urllib module itself as you're thinking about (as you mention urllib.close -- which doesn't exist).
The best approach: instead of x = urllib.urlopen(u) etc, use:
import contextlib
with contextlib.closing(urllib.urlopen(u)) as x:
...use x at will here...
The with statement, and the closing context manager, will ensure proper closure even in presence of exceptions.
A: You basically do need to explicitly close your connection when using IronPython. The automatic closing on going out of scope relies on the garbage collection. I ran into a situation where the garbage collection did not run for so long that Windows ran out of sockets. I was polling a webserver at high frequency (i.e. as high as IronPython and the connection would allow, ~7Hz). I could see the "established connections" (i.e. sockets in use) go up and up on PerfMon. The solution was to call gc.collect() after every call to urlopen.
A:
urllib.request module uses HTTP/1.1 and includes Connection:close header in its HTTP requests.
It's from official docs, you can check it here.
| |
doc_23537751
|
#guess image_name is the string
imgname = np.zeros(len(image_name))
for i in range(len(image_name)):
imgname[i] = ord(image_name[i])
and I load the encoded imgname in Lua with ffi.string as follow:
image_name = ffi.string(img_name:char():data()
but I got the error: fb15268637bc28e2175502f1a3bec6fb.jpg���7��R�, I google this error but find on answers, I was with python2.7 and LuaJIT.
Thanks in advance!
| |
doc_23537752
|
public boolean contains(String it) {
int index=front;
while(index!=-1){
if(dataList[index].equals(it)) {
return true;
}
index= nextList[index];
}
return false;
}
how does the .equals() comparison method affect the algorithmic complexity? Does it turn it from linear to quadratic?
A: You should take .equals() as a basic step when analysing the runtime of this algorithm. the important thing for computing the runtime of the algorithm is the size of dataList and in this sense the size of "it" is constant.
The best case complexity is given by the case of finding the element in the first position, and then is O(1), the worst case is when you find the element in the last position, and then is O(n). The average case is given by taking all the possibilities (that the element is in position one, or in position 2 and so on) and dividing by n, formally:
1+2+3+..+n/n
and this is O(n) too.
| |
doc_23537753
|
I passed the state object as dependency because i want to re-render
the component when values of settings object changes.
But it causes an infinite loop.
Update:
Let me clear my question more.
In my useEffect, I am calling my async function addTextItem() which calls the function finalPrice and it updates the state, but this way it causes infinite loop.
On other hand, If i call finalPrice in the useEffect directly instead of calling addTextItem then there is no infinite loop but it is also updating the state, right? then how this could be. & I need a solution as i have tried everything and now totally stuck.
Here is the code:
export default function CustomizerState(props) {
const initialText = "Hello"
const initialSize = {
x: REACT_APP_SIZE_X,
y: REACT_APP_SIZE_Y
}
const initialTextItem = {
id: generateID(),
text: "Hello",
font: fonts[0].value,
size: initialSize,
color: colors[0],
backplate: "cut-sharp",
uvPrint: false,
quantity: 1,
neonPrice: 0,
backplatePrice: 0,
neonPower: 0,
totalPrice: 0
}
const [settings, setSettings] = useState({
textItems: [],
libraryItems: [],
ownDesigns: [],
accessories: [
// My Objects here
],
finalPrice: 0
})
const addTextItem = async () => {
const pathLength = await textToPath(initialText, initialSize.x)
const { backplatePrice, neonPrice, neonPower, totalPrice } = calculateSvgPrice(pathLength)
const id = generateID()
const newItems = [
...settings.textItems,
{...initialTextItem, id, backplatePrice, neonPrice, neonPower, totalPrice}
]
finalPrice("textItems", newItems)
}
const finalPrice = (itemType = null, items = null) => {
const textItemsPrice = getTotalPrice()
const libraryItemsPrice = getTotalPrice("libraryItems")
const accessoriesPrice = getTotalPrice("accessories", "unitPrice")
const finalPrice = textItemsPrice + libraryItemsPrice + parseInt(accessoriesPrice)
if (itemType === null) {
setSettings((prevState) => (
{...prevState, finalPrice}
))
return false
}
setSettings((prevState) => (
{...prevState, [itemType]: items, finalPrice}
))
}
useEffect(() => {
// It will add first initial form item
addTextItem()
}, [JSON.stringify(settings)])
return (
<CustomizerContext.Provider value={{settings, addTextItem}}>
{props.children}
</CustomizerContext.Provider>
)
}
I have google and tried the solutions, but nothing worked for me. Can someone help me to fix this issue? I am stuck....
A: Check the useEffect hook documentation.
The array passed in the second argument array is the dependency array:
useEffect(() => {
//hook code
}, []);
The dependency array will make the hook code execute everytime any variable of the array changes. In your case you are changing the depency item settings in the call itself producing an infinite loop.
A: I forgot that when re-rendering happens, it also runs useEffect obviously and it causes setState again and again.
I managed to fix this by creating a state named initialItemCount with 0 initial value. I am checking if that state value is 0 then run addTextItem which will add my initial form item and updates the final price, but if the value 1 then only run the finalPrice function.
const [initialItemCount, setInitialItemCount] = useState(0)
useEffect(() => {
if (initialItemCount === 0) {
addTextItem()
setInitialItemCount(1)
}
if (initialItemCount === 1) {
finalPrice()
}
}, [JSON.stringify(settings)])
Finally, inner peace.
| |
doc_23537754
|
select t1.TQ
from table1 t1
left join table2 t2 on t1.comp_cd = t2.comp_cd and t1.plcy_frm = t2.plcy_frm
and t1.val_cd = t2.val_cd
The columns "comp_cd" and "plcy_frm" are fine, however the problem is with val_cd. Sometimes the val_cd in table2 does not map correctly to table1 and must go through a third table, table3. Table3 structure is below:
Val_Cd Mapped_Val_Cd
A123 A564
So -> I need to join on Mapped_Val_Cd value when it exists in Table3, but join on Val_Cd from Table2 when Val_Cd does not exist in Table3.
I hope this makes sense - I have tried Case when exists syntax but cannot get that to work.
A: Assuming there are no duplicates in table3, you can left join it in and then choose the value that you want in the on clause:
select t1.TQ
from table1 t1 left join
table3 t3
on t1.val_cd = t3.val_cd
table2 t2
on t1.comp_cd = t2.comp_cd and
t1.plcy_frm = t2.plcy_frm and
t1.val_cd = coalesce(t3.Mapped_Val_Cd, t2.val_cd);
| |
doc_23537755
|
Let's say I have a league where players compete against each other in 2 teams of 2 with RANDOM partners. They will then play 3 games:
Ex:
Court 1 has players A, B, C, and D: ABvsCD then ACvsBD then BCvsAD.
If I have 20 people in this league, and the league will go 24 weeks. How can I make sure that number of times that any 2 people end up on the same court as eachother MULTIPLE TIMES is distributed evenly amongst everyone?!
A: The trick is to minimize the sum of the square of the number of times 2 players play against each other.
See this video which explains how to implement such a fairness (or load balancing) constraint on a tennis scheduling problem at about 7 minutes into the video.
The example does both "number of times they play" fairness and "confrontation" fairness. Your description seems to indicate you're looking for "confrontation" fairness.
| |
doc_23537756
|
The parts that don't work are the click-through part, and the directx render. When I run it I basically have an invisible force field in front of all other windows and have to alt-tab around to visual studio to quickly press ALT F5 and end the debug (so at least the always on top and transparency works). I have been trying to figure out why those parts don't work, but my newbie c# skills fail me. hopefully someone can spot why and provide a modification.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Globalization;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System.Threading;
namespace MinimapSpy
{
public partial class Form1 : Form
{
private Margins marg;
//this is used to specify the boundaries of the transparent area
internal struct Margins
{
public int Left, Right, Top, Bottom;
}
[DllImport("user32.dll", SetLastError = true)]
private static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")]
static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
public const int GWL_EXSTYLE = -20;
public const int WS_EX_LAYERED = 0x80000;
public const int WS_EX_TRANSPARENT = 0x20;
public const int LWA_ALPHA = 0x2;
public const int LWA_COLORKEY = 0x1;
[DllImport("dwmapi.dll")]
static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins);
private Device device = null;
public Form1()
{
//Make the window's border completely transparant
SetWindowLong(this.Handle, GWL_EXSTYLE,
(IntPtr)(GetWindowLong(this.Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED ^ WS_EX_TRANSPARENT));
//Set the Alpha on the Whole Window to 255 (solid)
SetLayeredWindowAttributes(this.Handle, 0, 255, LWA_ALPHA);
//Init DirectX
//This initializes the DirectX device. It needs to be done once.
//The alpha channel in the backbuffer is critical.
PresentParameters presentParameters = new PresentParameters();
presentParameters.Windowed = true;
presentParameters.SwapEffect = SwapEffect.Discard;
presentParameters.BackBufferFormat = Format.A8R8G8B8;
this.device = new Device(0, DeviceType.Hardware, this.Handle,
CreateFlags.HardwareVertexProcessing, presentParameters);
Thread dx = new Thread(new ThreadStart(this.dxThread));
dx.IsBackground = true;
dx.Start();
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
//Create a margin (the whole form)
marg.Left = 0;
marg.Top = 0;
marg.Right = this.Width;
marg.Bottom = this.Height;
//Expand the Aero Glass Effect Border to the WHOLE form.
// since we have already had the border invisible we now
// have a completely invisible window - apart from the DirectX
// renders NOT in black.
DwmExtendFrameIntoClientArea(this.Handle, ref marg);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void dxThread()
{
while (true)
{
//Place your update logic here
device.Clear(ClearFlags.Target, Color.FromArgb(0, 0, 0, 0), 1.0f, 0);
device.RenderState.ZBufferEnable = false;
device.RenderState.Lighting = false;
device.RenderState.CullMode = Cull.None;
device.Transform.Projection = Matrix.OrthoOffCenterLH(0, this.Width, this.Height, 0, 0, 1);
device.BeginScene();
//Place your rendering logic here
device.EndScene();
//device.Present();
}
this.device.Dispose();
Application.Exit();
}
}
A: Here's a refined full sample code for making a window topmost - click through - transparent (= alpha blended). The sample makes a rotating color wheel which is rendered with DirectX, or actually with XNA 4.0, because I believe Microsoft has discontinued developing the managed directx and favours XNA today.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework.Graphics;
namespace ClickThroughXNA
{
public partial class Form1 : Form
{
// Directx graphics device
GraphicsDevice dev = null;
BasicEffect effect = null;
// Wheel vertexes
VertexPositionColor[] v = new VertexPositionColor[100];
// Wheel rotation
float rot = 0;
public Form1()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
Size = new System.Drawing.Size(500, 500);
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; // no borders
TopMost = true; // make the form always on top
Visible = true; // Important! if this isn't set, then the form is not shown at all
// Set the form click-through
int initialStyle = GetWindowLong(this.Handle, -20);
SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20);
// Create device presentation parameters
PresentationParameters p = new PresentationParameters();
p.IsFullScreen = false;
p.DeviceWindowHandle = this.Handle;
p.BackBufferFormat = SurfaceFormat.Vector4;
p.PresentationInterval = PresentInterval.One;
// Create XNA graphics device
dev = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile.Reach, p);
// Init basic effect
effect = new BasicEffect(dev);
// Extend aero glass style on form init
OnResize(null);
}
protected override void OnResize(EventArgs e)
{
int[] margins = new int[] { 0, 0, Width, Height };
// Extend aero glass style to whole form
DwmExtendFrameIntoClientArea(this.Handle, ref margins);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
// do nothing here to stop window normal background painting
}
protected override void OnPaint(PaintEventArgs e)
{
// Clear device with fully transparent black
dev.Clear(new Microsoft.Xna.Framework.Color(0, 0, 0, 0.0f));
// Rotate wheel a bit
rot+=0.1f;
// Make the wheel vertexes and colors for vertexes
for (int i = 0; i < v.Length; i++)
{
if (i % 3 == 1)
v[i].Position = new Microsoft.Xna.Framework.Vector3((float)Math.Sin((i + rot) * (Math.PI * 2f / (float)v.Length)), (float)Math.Cos((i + rot) * (Math.PI * 2f / (float)v.Length)), 0);
else if (i % 3 == 2)
v[i].Position = new Microsoft.Xna.Framework.Vector3((float)Math.Sin((i + 2 + rot) * (Math.PI * 2f / (float)v.Length)), (float)Math.Cos((i + 2 + rot) * (Math.PI * 2f / (float)v.Length)), 0);
v[i].Color = new Microsoft.Xna.Framework.Color(1 - (i / (float)v.Length), i / (float)v.Length, 0, i / (float)v.Length);
}
// Enable position colored vertex rendering
effect.VertexColorEnabled = true;
foreach (EffectPass pass in effect.CurrentTechnique.Passes) pass.Apply();
// Draw the primitives (the wheel)
dev.DrawUserPrimitives(PrimitiveType.TriangleList, v, 0, v.Length / 3, VertexPositionColor.VertexDeclaration);
// Present the device contents into form
dev.Present();
// Redraw immediatily
Invalidate();
}
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("dwmapi.dll")]
static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref int[] pMargins);
}
}
A: A little extension/modification to Jaska's code, which the form is transparent
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.TopMost = true; // make the form always on top
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; // hidden border
this.WindowState = FormWindowState.Maximized; // maximized
this.MinimizeBox = this.MaximizeBox = false; // not allowed to be minimized
this.MinimumSize = this.MaximumSize = this.Size; // not allowed to be resized
this.TransparencyKey = this.BackColor = Color.Red; // the color key to transparent, choose a color that you don't use
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
// Set the form click-through
cp.ExStyle |= 0x80000 /* WS_EX_LAYERED */ | 0x20 /* WS_EX_TRANSPARENT */;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// draw what you want
e.Graphics.FillEllipse(Brushes.Blue, 30, 30, 100, 100);
}
}
A: Change your extended window style to only WS_EX_LAYERED, window style to only WS_POPUP (NO WS_SIZEBOX) and make sure to use DwmExtendFrameIntoClientArea with all -1's and this will produce transparent windows with layered support: downside is you need to bltbit with GDI from an offscreen directx rendering. Not optimal but it works. This gives mouse click throughs + directx rendering + transparency. Downside is you'll need to inform GDI anytime, pull the directx buffer (all of it or just the damaged portions) and write them to the screem with bltbit.
Setting the extended window style to WS_EX_COMPOSITED and DwmExtendedFrameIntoClientArea with all -1's (similar as above, WS_POPUP on the regular window style). This you can run directx from but no mouse clickthroughs. You can at this point define irregular paths for the hit mask and pass it to windows, its not perfect but if you know a general (non regular) area that can pass-through it'll work.
Still trying to find a true way of using opengl/directx on mac or windows platforms that can pass through mouse clicks with out having to do a bitblt to a legacy rendering system.
A: I have a simple way use TransparentKey property and a 1x1 pixel label with the color of Form TransparentKey.
On Form and all control MouseMouse event. Set label position to Mouse location.
private void MoveHole()
{
var newLocation = PointToClient(MousePosition);
lblHole.Location = newLocation;
}
| |
doc_23537757
|
wget http://nodejs.org/dist/node-v0.4.10.tar.gz
tar -zxvf node-v0.4.10.tar.gz
cd node-v0.x.x
./configure --prefix=~/node
make
make test
make install
this should set me up with a nodejs install under ~/node however, during the ./configure --prefix=~/node I encounter the this in the dependency requirement:
node-v0.4.10]$ ./configure --prefix=~/node
Checking for program g++ or c++ : /usr/bin/g++
Checking for program cpp : /usr/bin/cpp
Checking for program ar : /usr/bin/ar
Checking for program ranlib : /usr/bin/ranlib
Checking for g++ : ok
Checking for program gcc or cc : /usr/bin/gcc
Checking for program ar : /usr/bin/ar
Checking for program ranlib : /usr/bin/ranlib
Checking for gcc : ok
Checking for library dl : yes
Checking for openssl : not found
Checking for function SSL_library_init : not found
Checking for header openssl/crypto.h : not found
/opt/server/node-v0.4.10/wscript:341: error: Could not autodetect OpenSSL support. Make sure OpenSSL development packages are installed. Use configure --without-ssl to disable this message.
[tomcat@test.dev node-v0.4.10]$ make
Project not configured (run 'waf configure' first)
make: *** [program] Error 1
I have checked that open ssl is on the box:
node-v0.4.10]$ openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013
~]$ gcc -v
Using built-in specs.
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre --enable-libgcj-multifile --enable-java-maintainer-mode --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --disable-libjava-multilib --with-ppl --with-cloog --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)
Not sure what other dependencies their are, been looking for a config file
A: Node.js is already packaged for the most popular distributions.
If my guess is right, and you're using CentOS 6 or similar, the following command should work fine:
sudo yum install nodejs npm --enablerepo=epel
| |
doc_23537758
|
in ruby i notice a lot of people do this:
do_something(with params) if 1 = 1
is there any difference (even slight) between that and this:
if 1 = 1 do_something(with params)
or is it the same thing written for better clarity?
A: The latter is syntactically invalid. You would need to write:
if 1==1 then do_something(with params) end
Single-line conditionals must always trail. And yes, there is a difference. Try these out:
bar1 = if foo1=14
foo1*3
end
#=> 42
bar2 = foo2*3 if foo2=14
#=> NameError: undefined local variable or method `foo2' for main:Object
In the latter, Ruby sees the assignment after the reference and so treats foo2 as a method instead of a local variable. This is only an issue when:
*
*You are intentionally using assignment (not testing for equality) in a conditional, and
*This is the first time (in terms of source order) that this variable has been assigned in the scope.
A: Fire up irb and run your code and you will learn:
*
*1=1 is a syntax error, change to 1==1.
*You can't have an expression directly after if 1==1, you will have to add a : or then and close with an end.
The trailing if should really only be used for single expressions and you can't add an else. They are called statement modifiers and they are just syntactic sugar for better readability. I'm not totally against them but recommend using them sparingly.
A: It's syntactic sugar... allowing us to write code in a way that's easier to read.
http://rubylearning.com/satishtalim/ruby_syntactic_sugar.html
Note: for @Phrogz, the following are NOT the same!
Please make sure that you are not trying to assign a value to variable instead of comparing a variable to a value! Also, as Phrogz mentions, the order of variable assignment makes a big difference... see @Phrogz answer for mor details!
if 1 = 1 then do_something(with params) end
if 1 == 1 then do_something(with params) end
A: You can use either but if you put the if statement first then you will need to close the condition with an 'end'.
if 1==1
do_something(with params)
end
A: The following leaves foo as nil.
foo = true unless defined?(foo) #Leaves foo as nil
This is because Ruby creates a variable foo and assigns it to nil when it reads (parsing, I think) the foo = true bit, and then when it reads (executing, I think) the unless defined?(foo), it says that foo is defined (it's defined as nil), and therefore doesn't execute the foo = true part.
If you did
unless defined?(foo)
foo = true
end
then you'd get foo assinged to true.
I added this to What are the Ruby Gotchas a newbie should be warned about?, because someone got confused about it here.
So yes, in some circumstances it can matter.
| |
doc_23537759
|
if let domain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: domain)
}
With the code above, there are "random cases" where UserDefault was not cleared so I can only assume that the Bundle.main.bundleIdentifier is nil thus the statement were not executed. This is needed in our app otherwise the app will crash if the "old UserDefault" be use and we received number of crash logs because of this.
Thanks!
| |
doc_23537760
|
The above question is in reference to when working with HTMLElementObjects as variables.
Google Chrome's extension development example shows this in the below function:
let current = event.target.parentElement.querySelector(
`.${selectedClassName}`
);
if (current && current !== event.target) {
current.classList.remove(selectedClassName);
}
let color = event.target.dataset.color;
event.target.classList.add(selectedClassName);
chrome.storage.sync.set({ color });
}
Why does it have to be "current && current"? It doesn't work with just "current !== event.target"
Link to full article for reference: https://developer.chrome.com/docs/extensions/mv3/getstarted/#logic
A: This is because of JavaScript's operator precedence:
11: Strict Inequality (!==)
...
7: Logical AND (&&)
Since strict inequality has a higher precedence than logical AND, it's functionally equivalent to the following:
(current) && (current !== event.target)
The people who wrote the tutorial likely did not want this expression to evaluate as true if current was any kind of falsey value. By doing this, they ensure that event.target can't just be any old value and still pass.
A: What it does is checks if current is truthy AND is not equal to event.target. If event.target and current are both null it will still return false
A: The first Var checking in var && var... is checking if var is not null or undefined and then compare It with var2
In fact, you could write It like that :
If (var !== null || var !== undefined || var !== false) {
return var !== var2
}
| |
doc_23537761
|
<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
Mage::register('isSecureArea', 1);
$product = Mage::getModel('catalog/product');
$product->setSku("ABC123");
$product->setName("Name");
$product->setDescription("Desc.");
$product->setShortDescription("Desc2.");
$product->setPrice(70.50);
$product->setTypeId('simple');
$product->setAttributeSetId(9);
$product->setCategoryIds("20,24");
$product->setWeight(1.0);
$product->setTaxClassId(2);
$product->setVisibility(4);
$product->setStatus(1);
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
$product->save();
?>
The problem is the result:
Fatal error: Uncaught exception
'PDOException' with message 'SQLSTATE[23000]: Integrity constraint
violation: 1452 Cannot add or update a child row: a foreign key
constraint fails (magento.catalog_product_entity, CONSTRAINT
FK_CAT_PRD_ENTT_ATTR_SET_ID_EAV_ATTR_SET_ATTR_SET_ID FOREIGN KEY
(attribute_set_id) REFERENCES eav_attribute_set
(attribute_set_i)' in
/home/zelewe3k/public_html/lib/Zend/Db/Statement/Pdo.php:228 Stack
trace: #0
/home/zelewe3k/public_html/lib/Zend/Db/Statement/Pdo.php(228):
PDOStatement->execute(Array) #1
/home/zelewe3k/public_html/lib/Varien/Db/Statement/Pdo/Mysql.php(110):
Zend_Db_Statement_Pdo->_execute(Array) #2
/home/zelewe3k/public_html/app/code/core/Zend/Db/Statement.php(291):
Varien_Db_Statement_Pdo_Mysql->_execute(Array) #3
/home/zelewe3k/public_html/lib/Zend/Db/Adapter/Abstract.php(480):
Zend_Db_Statement->execute(Array) #4
/home/zelewe3k/public_html/lib/Zend/Db/Adapter/Pdo/Abstract.php(238):
Zend_Db_Adapter_Abstract->query('INSERT INTOca...', Array) #5
/home/zelewe3k/pu in
/home/zelewe3k/public_html/lib/Zend/Db/Statement/Pdo.php on line 234
What can I do?
How to fix it!?
A: Its looks like attribute set id 9 does not exist .Please check you attribute set id is exists in Magento or try
$product->setAttributeSetId(4);
| |
doc_23537762
|
1.My first task is to calculate average r,g,b color component of the test
region
(1251, 532, 589, 82)
for that i have written below pseudo code which give
me ouput as
(217, 15, 28)
import cv2
from PIL import Image
import math
import numpy as np
class CompareColor(object):
''' loop through each pixel and average rgb '''
def __init__(self, imageName):
self.pic = Image.open(imageName)
# load image data
self.imgData = self.pic.load()
pixel_values = list(self.pic.getdata())
print(pixel_values)
def color(self):
r, g, b = 0, 0, 0
count = 0
for x in range(self.pic.size[0]):
for y in range(self.pic.size[1]):
tempr,tempg,tempb = self.imgData[x,y]
r += tempr
g += tempg
b += tempb
count += 1
# calculate averages
return math.ceil(r/count), math.ceil(g/count), math.ceil(b/count)
class ColorTest:
def __init__(self):
self.actualImgPath = "/home/color/youtube.png"
self.includedAreas = (1251, 532, 589, 82)
def findActualRGBComponent(self):
actualImg = cv2.imread(self.actualImgPath)
Y1 = self.includedAreas[1]
Y2 = Y1 + self.includedAreas[3]
X1 = self.includedAreas[0]
X2 = X1 + self.includedAreas[2]
crop_image = actualImg[Y1:Y2, X1:X2].copy()
status = cv2.imwrite('//home//color//crop.png', crop_image)
img_file = '//home//color//crop.png'
pc = CompareColor(img_file)
print('color', pc.color())
if __name__ == "__main__":
colTest = ColorTest()
colTest.findActualRGBComponent()
*My second task is to find the flatness of color which means how flat the color is - whether there is much variation across the area of interest in the range 0-100 where 100 is perfect single color but i am not able to figure out how to implement this logic. Can any one please help me
A: You should check this answer about the dominant colors of the image, because finding an average on that particular picture has no practical meaning, the average color does not exist anywhere on the picture: How to find the average colour of an image in Python with OpenCV?
And once you're done with the dominant colors, you'll easily answer the second question about the flatness or whatever -- because the mean color you've found so far does not exist on the picture, so the flatness can be an arbitrary number for a non-existing color.
| |
doc_23537763
|
foreach ($giftCardSchemeData as $keypreload => $preload) {
for ($i=0; $i <$preload['quantity'] ; $i++) {
$cardid = new CarddetailsId($uuidGenerator->generate());
$cardnumber = self::getCardNumber();
$cardexistencetype = ($key == "giftCardSchemeData") ? "Physical" : "E-Card" ;
$giftCardSchemeDataDb = array('preload' => array('value' => $preload['value'], 'expirymonths' => $preload['expiryMonths']));
$otherdata = array('cardnumber' => $cardnumber, 'cardexistencetype' => $cardexistencetype, 'isgiftcard' => true , 'giftcardamount' => $preload['value'],'giftCardSchemeData' => json_encode($giftCardSchemeDataDb), 'expirymonths' => $preload['expiryMonths'], 'isloyaltycard' => false, 'loyaltypoints' => null,'loyaltyCardSchemeData' => null, 'loyaltyRedeemAmount' => null, 'pinnumber' => mt_rand(100000,999999));
$output = array_merge($data, $otherdata);
// var_dump($output);
$carddetailsRepository = $this->get('oloy.carddetails.repository');
$carddetails = $carddetailsRepository->findByCardnumber($cardnumber);
if (!$carddetails) {
$commandBus->dispatch(
new CreateCarddetails($cardid, $output)
);
} else {
self::generateCardFunctionForErrorException($cardid, $output, $commandBus);
}
}
}
Like above foreach I am having totally 5 of them. When I call the function each time the 5 foreach runs and then return the response. It take more time and the php maximum execution time occurs.
Is there a any way to send the response and then we could run the foreach in server side and not creating the maximum execution time issue.Also need an optimization for the foreach.
Also In symfony I have tried the try catch method for the existence check in the above code it return the Entity closed Error. I have teprorily used the existence check in Db but need an optimization
A: There seems to be a lot wrong (or to be optimized) with this code, but let's focus on your questions:
First I think this code shouldn't be in code that will be triggered by a visitor.
You should seperate 2 processes:
1. A cronjob that runs that will generate everything that must be generated and saved that generated info to a database. The cronjob can take as much time as it needs. Look at Symfony's console components
2. A page that displays only the generated info by fetching it from the database and passing it to a Twig template.
However, looking at the code you posted I think it can be greatly optimized as is. You seem to have a foreach loop that fetches variable data, and in that you have a for-loop that does not seem to generate much variability at all.
So most of the code inside the for loop is now being executed over and over again without making any actual changes.
Here is a concept that would give much higher performance. Ofcourse since I don't know the actual context of your code you will have to "fix it".
$carddetailsRepository = $this->get('oloy.carddetails.repository');
$cardexistencetype = ($key == "giftCardSchemeData") ? "Physical" : "E-Card";
foreach ($giftCardSchemeData as $keypreload => $preload) {
$cardnumber = self::getCardNumber();
$carddetails = $carddetailsRepository->findByCardnumber($cardnumber);
$giftCardSchemeDataDb = array('preload' => array('value' =>
$preload['value'], 'expirymonths' => $preload['expiryMonths']));
$otherdata = array('cardnumber' => $cardnumber, 'cardexistencetype' =>
$cardexistencetype, 'isgiftcard' => true , 'giftcardamount' =>
$preload['value'],'giftCardSchemeData' =>
json_encode($giftCardSchemeDataDb), 'expirymonths' =>
$preload['expiryMonths'], 'isloyaltycard' => false, 'loyaltypoints' =>
null,'loyaltyCardSchemeData' => null, 'loyaltyRedeemAmount' => null,
'pinnumber' => 0);
$output = array_merge($data, $otherdata);
for ($i=0; $i <$preload['quantity'] ; $i++) {
$cardid = new CarddetailsId($uuidGenerator->generate());
$output['pinnumber'] = mt_rand(100000,999999);
if (!$carddetails) {
$commandBus->dispatch(
new CreateCarddetails($cardid, $output)
);
} else {
self::generateCardFunctionForErrorException($cardid, $output, $commandBus);
}
}
}
Also: if in this code you are triggering any database inserts or updates, you don't want to trigger them each iteration. You will want to start some kind of database transaction and flush the queries each X iterations instead.
| |
doc_23537764
|
let
Source = Web.Page(Web.Contents(**"https://coinmarketcap.com/currencies/eos/historical-data/?start=20130428&end=20180309"**)),
Data0 = Source{0}[Data],
#"Changed Type" = Table.TransformColumnTypes(Data0,{{"Date", type date}, {"Open", type number}, {"High", type number}, {"Low", type number}, {"Close", type number}, {"Volume", type number}, {"Market Cap", type number}}),
#"Sorted rows" = Table.Sort(#"Changed type",{{"Date", Order.Ascending}})
in
#"Sorted rows"
I used CONCATENATE to create a link which uses the today date(same format) as the end date so it updates every day. How do I reference the cell which contains the link in Web.Contents? I haven't used Power Query before and I would appreciate it if someone could walk me through the steps. I am really frustrated that such a simple and certainly very used operation doesn't have a ready made solution. Referencing a static web link is straightforward but absolutely useless.
Thanks very much in advance for any responses.
A: You can refer to a cell in an Excel sheet, using syntax like:
Excel.CurrentWorkbook(){[Name=MyRangeName]}[Content]{0}[Column1]
That will lookup the value in table/named range: MyRangeName, at the 1st row, 1st column.
Pass that expression as the 1st parameter for Web.Contents.
When EOS takes off, you owe me a lambo ...
| |
doc_23537765
|
Below is my current dockerfile:
FROM rocker/tidyverse:latest
RUN mkdir -p $HOME/.R
COPY R/Makevars /root/.R/Makevars
RUN apt-get update -qq \
&& apt-get -y --no-install-recommends install \
liblzma-dev \
libbz2-dev \
ed \
clang \
ccache \
default-jdk \
default-jre \
&& R CMD javareconf \
&& install2.r --error \
ggstance ggrepel \
rstan shinystan rstanarm \
###My pkgs
tidytext janitor corrr officer devtools pacman
tidyquant timetk tibbletime sweep broom prophet \
forecast prophet lime sparklyr rsparkling \
formattable httr rvest xml2 jsonlite \
textclean ggthemes naniar \
&& Rscript -e 'devtools::install_github(c("hadley/multidplyr","jeremystan/tidyjson","ropenscilabs/skimr"))' \
&& rm -rf /tmp/downloaded_packages/ /tmp/*.rds \
&& rm -rf /var/lib/apt/lists/*
A: save this to something like package_check.R and then have a Docker line that runs it via Rscript:
c("tidytext", "janitor", "corrr", "officer", "devtools", "pacman", "tidyquant",
"timetk", "tibbletime", "sweep", "broom", "prophet", "forecast", "prophet",
"lime", "sparklyr", "rsparkling", "formattable", "httr", "rvest", "xml2",
"jsonlite", "textclean", "ggthemes", "naniar") -> chk_pkgs
suppressPackageStartupMessages(
sapply(chk_pkgs, require, character.only=TRUE, quietly=FALSE, warn.conflicts=FALSE)
) -> ret
missing_pkgs <- sort(names(which(ret == FALSE)))
if (length(missing_pkgs) > 0) {
warning("The following packages are not installed: %s",
paste0(sprintf(" - %s", missing_pkgs), collapse="\n"))
}
quit(save=FALSE, status=length(names) == 0, runLast = FALSE)
That will give you a missing package error with the missing list and exit the script with a non-zero exit status.
A: I am using the following line to stop building the Docker image upon not finding the package you would like to install:
RUN R -e 'stopifnot("devtools" %in% installed.packages()[,"Package"])'
Make sure to replace devtools with the name of the package you are trying to install.
| |
doc_23537766
|
But 'git push' is not doing its job. It does all the local processing but gets stuck at the last step. How can I resolve this?
I did the following:
git checkout master
git merge --no-ff dev_08_15
git commit -a -m "dev_08_15 Merge commit"
git push origin master
And now git is stuck at this place. Below is the output I get.
Counting objects: 61, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (19/19), done.
Writing objects: 100% (28/28), 2.20 KiB, done.
Total 28 (delta 14), reused 0 (delta 0)
I can pull the changes which others are pushing. But I can't push any of my changes now.
| |
doc_23537767
|
As you can see there is a Tale Model and Purpose Model and a Has_many_through join model TalePurposeJoin
Now the join table has data as [4,3] but on query tale.purpose_ids I get [3,4]
I want to retain the db order.
What is activerecord doing behind the scene, why and how do I stop it.
Here is the query sql is generating
SELECT "purposes".id FROM "purposes" INNER JOIN "tale_purpose_joins" ON "purposes"."id" = "tale_purpose_joins"."purpose_id" WHERE "tale_purpose_joins"."tale_id" = ? [["tale_id", 1]]
| |
doc_23537768
|
When retrieving recordsets, the application uses the Bang (!) operators to access the fields in the recordsets Eg RS!OrderId.
Whilst I am aware of this practice, I have never actually used it(except when I have been lazy), Neither have I used RS("OrderId") as I have always (or usually) used the fully qualified method (eg RS.fields("OrderId").value. or even expanded it further using the .Item Property.)
Both return exactly the same value, one is shorter to type than the other.
The reason I have stuck to this method is that sometime in the far distant past, I believe I was told that it was more performant to fully qualify the field, as the code had to translated each occurrence of the ! operator to its fully qualified sister. However, the ! operator reduces typing and as such dev time.
I also seem to recall that the ! for ADO was going to be deprecated at some point in the future. But it still seems to be around in code I just wondered which method is regarded as best practice and which one performs better over the other.
A: I have thoroughly tested performance of VB6 and ADO for use in my application. The absolute quickest way to get data from a recordset is to use the FIELD object. You will notice a big difference in performance when returning a lot of rows. The following is a block of code from my application (reduced to highlight the proper use of field objects).
Dim fMinLongitude As ADODB.Field
Dim fMinLatitude As ADODB.Field
Dim fMaxLongitude As ADODB.Field
Dim fMaxLatitude As ADODB.Field
Dim fStreetCount As ADODB.Field
If RS.RecordCount = 0 Then
Exit Sub
End If
Set fMinLongitude = RS.Fields.Item("MinLongitude")
Set fMinLatitude = RS.Fields.Item("MinLatitude")
Set fMaxLongitude = RS.Fields.Item("MaxLongitude")
Set fMaxLatitude = RS.Fields.Item("MaxLatitude")
Set fStreetCount = RS.Fields.Item("StreetCount")
While Not RS.EOF
LineGridCount = LineGridCount + 1
With LineGrid(LineGridCount)
.MinLongitude = fMinLongitude.Value
.MaxLongitude = fMaxLongitude.Value
.MinLatitude = fMinLatitude.Value
.MaxLatitude = fMaxLatitude.Value
End With
RS.MoveNext
Wend
RS.Close
Set RS = Nothing
Note that I set field objects for 5 columns returned by a SQL Server stored procedure. I then use them inside a loop. When you do RS.MoveNext, it affects the field objects.
With the code shown above, I can load 26,000 rows into my user defined type in less than 1 second. In fact, running through code it took 0.05 seconds. In the compiled application it's even faster.
If you do not use field objects, then you should at least use a WITH block. As mentioned in another post, using ordinal position is faster than other alternative (with the exception of the field method). If you plan on using ordinal position, then you should use a WITH block. For example:
With RS.Fields
ID = .Item(0).Value
Name = .Item(1).Value
EyeColor = .Item(2).Value
End With
Using a with block is nice because it reduces the amount of typing and at the same time it speeds up the execution of the code. This performance increase occurs because VB can set a pointer to the field object once and then reuse that pointer for each call to the fields object.
By the way... I dislike the "less typing" argument. I often find that better performing code is also more complex code. With VB6's intellisense, the extra typing isn't all that much either.
RS("FieldName") is 15 characters.
I've gotten in to the habit of typing: r s (dot) f (dot) i (open parenthesis) (quote) FieldName (quote) (Close Parenthesis) (dot) v. This is 6 extra key presses for using the fully qualified method.
Using the with block method, it would be (dot) i (open parenthesis) (quote) FieldName (quote) (close parenthesis) (dot) v, which is 17 key presses.
This is one of those situations where a good habit takes little effort and pays off big by having better performing code.
I just did some performance testing. The following test uses a client side cursor which means that all of the data returned by the query is copied to the client computer and stored within the recordset object.
The code I used for the performance test is this:
Private Sub Command1_Click()
Dim DB As ADODB.Connection
Dim RS As ADODB.Recordset
Dim Results() As String
Set DB = New ADODB.Connection
DB.ConnectionString = "my connection string here"
DB.CursorLocation = adUseClient
DB.Open
Set RS = New ADODB.Recordset
Call RS.Open("Select * From MapStreetsPoints", DB, adOpenForwardOnly, adLockReadOnly)
Dim Start As Single
Dim FeatureId As Long
Dim PointNumber As Long
Dim Longitude As Single
Dim Latitude As Single
Dim fFeatureId As ADODB.Field
Dim fPointNumber As ADODB.Field
Dim fLongitude As ADODB.Field
Dim fLatitude As ADODB.Field
ReDim Results(5)
RS.MoveFirst
Start = Timer
Do While Not RS.EOF
FeatureId = RS!FeatureId
PointNumber = RS!PointNumber
Longitude = RS!Longitude
Latitude = RS!Latitude
RS.MoveNext
Loop
Results(0) = "Bang Method: " & Format(Timer - Start, "0.000")
RS.MoveFirst
Start = Timer
Do While Not RS.EOF
FeatureId = RS.Fields.Item("FeatureId").Value
PointNumber = RS.Fields.Item("PointNumber").Value
Longitude = RS.Fields.Item("Longitude").Value
Latitude = RS.Fields.Item("Latitude").Value
RS.MoveNext
Loop
Results(1) = "Fully Qualified Name Method: " & Format(Timer - Start, "0.000")
RS.MoveFirst
Start = Timer
Do While Not RS.EOF
FeatureId = RS.Fields.Item(0).Value
PointNumber = RS.Fields.Item(1).Value
Longitude = RS.Fields.Item(2).Value
Latitude = RS.Fields.Item(3).Value
RS.MoveNext
Loop
Results(2) = "Fully Qualified Ordinal Method: " & Format(Timer - Start, "0.000")
RS.MoveFirst
Start = Timer
With RS.Fields
Do While Not RS.EOF
FeatureId = .Item("FeatureId").Value
PointNumber = .Item("PointNumber").Value
Longitude = .Item("Longitude").Value
Latitude = .Item("Latitude").Value
RS.MoveNext
Loop
End With
Results(3) = "With Block Method: " & Format(Timer - Start, "0.000")
RS.MoveFirst
Start = Timer
With RS.Fields
Do While Not RS.EOF
FeatureId = .Item(0).Value
PointNumber = .Item(1).Value
Longitude = .Item(2).Value
Latitude = .Item(3).Value
RS.MoveNext
Loop
End With
Results(4) = "With Block Ordinal Method: " & Format(Timer - Start, "0.000")
RS.MoveFirst
Start = Timer
Set fFeatureId = RS.Fields.Item("FeatureId")
Set fPointNumber = RS.Fields.Item("PointNumber")
Set fLatitude = RS.Fields.Item("Latitude")
Set fLongitude = RS.Fields.Item("Longitude")
Do While Not RS.EOF
FeatureId = fFeatureId.Value
PointNumber = fPointNumber.Value
Longitude = fLongitude.Value
Latitude = fLatitude.Value
RS.MoveNext
Loop
Results(5) = "Field Method: " & Format(Timer - Start, "0.000")
Text1.Text = "Rows = " & RS.RecordCount & vbCrLf & Join(Results, vbCrLf)
End Sub
The results are:
Rows = 2,775,548
Bang Method: 9.441
Fully Qualified Name Method: 9.367
Fully Qualified Ordinal Method: 5.191
With Block Method: 8.527
With Block Ordinal Method: 5.117
Field Method: 4.316
Clearly the field method is the winner. It takes less than 1/2 the time of the bang method. Also notice that the ordinal methods also have decent performance compared to field method.
A: Bill Vaughn had a good discussion of this in his article "ADO Performance Best Practices". The conclusion, as indicated by Alex K in the comment, is to use an ordinal such as rs(0) or rs(7).
Bill also discussed a technique of using an enum to provide readable names for the index positions. For example, with a query like:
SELECT CatName, CatType, CatSize from Cats Where...
You could have this enum in VB:
Enum enuCatsQuery
CatName
CatType
CatSize
End Enum
And this code to access the field:
StrMyName = Rs(enuCatsQuery.CatName)
| |
doc_23537769
|
my $vstup = "C:/Users/Omega/Documents/Kontroly/testkontroly/kontroly20220513_154743.txt";
my $log = "C:/Users/Omega/Documents/Kontroly/testkontroly/kontroly.log";
open( my $default_fh, "<", $vstup ) or die $!;
open( my $main_fh, ">", $log ) or die $!;
my $var = 0;
while ( <$default_fh> ) {
if (/\Volat\b/)
$var = 1;
}
if ( $var )
print $main_fh $_;
}
}
close $default_fh;
close $main_fh;
A: The approach below use one semaphore variable and a buffer variable to enable the desired behavior.
Notice that the pattern used was replaced by 'A` for simplicity testing.
#!/usr/bin/perl
use strict;
use warnings;
my ($in_fh, $out_fh);
my ($in, $out);
$in = 'input.txt';
$out = 'output.txt';
open($in_fh, "< ", $in) || die $!."\n";
open($out_fh, "> ", $out) || die $!;
my $p_next = 0;
my $p_line;
while (my $line = <$in_fh>) {
# print line after occurrence
print $out_fh $line if ($p_next);
if ($line =~ /A/) {
if (defined($p_line)) {
# print previous line
print $out_fh $p_line;
# once printed undefine variable to avoid printing it again in the next loop
undef($p_line);
}
# Print current line if not already printed as the line follows a pattern
print $out_fh $line if (!$p_next);
# toggle semaphore to print the next line
$p_next = 1;
} else {
# pattern not found.
# if pattern was not detected in both current and previous line.
$p_line = $line if (!$p_next);
$p_next = 0;
}
}
close($in_fh);
close($out_fh);
| |
doc_23537770
|
I have looked on here as well as my college textbook and cannot find a clear answer. The answers that I have seen use C functions to handle the output, I am trying to stay away from C because I really want to understand how Assembly works.
Anyways, the program below does 2 things. The first thing it does is loop x number of times and print "hello" to the console each iteration. Everything is working fine in this section of the program
The second part is also a loop, but instead of printing a string, I only want to print an index of the string.
This is an example in C of what i'm trying to do:
char hello[6] = "Hello";
int len = 6;
for (int i=0; i<len; i++)
{
printf("%c\n", hello[i]);
}
This is where I am having trouble, it is not printing anything at all. I have tried the following instructions to print the character value to the console: MOV LDR LDRB.
I know this is probably something very simple, any help is appreciated.
Here is the code, I've commented everything to show what 'I think' is happening:
/*
* Program: String Loop
*
* Author:
*
* Date: 1/29/20
*
* Purpose: Learning ARM Assembly Language
*/
.text
.global main
main:
printString:
MOV R3, #0 @ Store counter in r3
MOV R4, #5 @ Max iterations for loop1
loop1:
@ Print String
MOV R7, #4 @ Syscall Write
MOV R0, #1 @ Output to monitor
LDR R2, =len @ Buffer size
LDR R1, =message @ Addr of string
SWI 0 @ Interrupt
ADD R3, R3, #1 @ Incr counter
CMP R3, R4 @ Compare counter/max iterations
BLT loop1 @ If counter < max, loop again
printChar:
LDR R4, =message @ Load string addr into r4
loop2:
LDRB R5, [R4], #1 @ Get next char of string
CMP R5, #0 @ See if char is #0
BEQ exit @ If so, exit
@ Print Char
MOV R7, #4
MOV R0, #1
MOV R2, #1
MOV R1, R5 // Also tried LDR R1, [R5] && LDRB R1, [R5]
SWI 0
B loop2
exit:
MOV R7, #1
SWI 0
.data
message:
.ascii "Hello\n"
len = .-message
.end
A: .data
message1:
.ascii "Hello\n"
len1 = . - message1
message2:
.byte 0
len2 = . - message2
.text
.global _start
_start:
ldr r0, =message2
ldr r1, =len2
ldr r3, =message1
ldr r4, =len1
mov r5, #0
loop$:
ldr r6, [r3, r4]
strb r6, [r0]
bl print
cmp r5, r4
addlt r4, #1
blt loop$
mov r7, #1
mov r0, #0
svc #0
print:
mov r2, r1
mov r1, r0
mov r0, #1
mov r7, #4
svc #0
mov pc, lr
| |
doc_23537771
|
export function useSort<PossibleType>(
delay: number,
array: PossibleType extends "MainPanel.tsx" ? Chat[] : PossibleType extends "NewGroup.tsx" ? NewGroupMember[] : [],
type: PossibleType
) {
const [rawInput, setRawInput] = useState("");
const [filteredData, setFilteredData] = useState<Chat[]>([]);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => setRawInput(e.target.value.toLowerCase());
const delayedInput = useDebounce(rawInput, delay);
useEffect(() => {
if (!delayedInput || delayedInput.length <= 1) return setFilteredData(array);
let result = [];
switch (type) {
case "MainPanel.tsx":
result = array.filter((data) => data.chatName.search(delayedInput) != -1);
break;
case "NewGroup.tsx":
result = array.filter((data) => data.email.search(delayedInput) != -1);
default:
result = array;
}
setFilteredData(result);
}, [delayedInput, array]);
return { rawInput, handleChange, delayedInput, filteredData };
A: What you are trying to do it run different pieces of code depending on what type is passed into the function ie function overloading. Unfortunately typescript does not add compile time function overloading or equivalent methods. You would have to do it the same way as in javascript for example using instanceof or typeof etc.
| |
doc_23537772
|
I have three views in my app, View1, View2, View3.
I know how to go from View1 to View2, and from View2 to View3, but how do I go from View3 back to View1?
I am using the following method in the View1ViewController.m to go from View1 to View2:
[self presentModalViewController:view2ViewController animated:YES]
And the same thing to go from View2 to View3.
I am including the View2 view controller in the View1 XIB file, and am including the View3 view controller in the View2 XIB file.
I've found that if I use [self dismissModalViewControllerAnimated:YES] from View3 I can only go back to View2, whereas I need to go all the way back to View1.
Any help/direction would be greatly appreciated.
Many thanks,
-Sd
A: Don't think of calling -presentModalViewController: as a way of going from one view controller to another; think of it as a way of, well, presenting a view controller modally. If you want to implement navigation, you should take a look at UINavigationController.
A: From your description, it sounds like you're using modal views incorrectly. They are not a way to transition between views, they are a way to briefly show some dialog that will be dismissed soon after (like selecting a date or something). Are you sure that both your views are actually modal views, and not completely distinct?
A: You might consider using a navigation controller to switch between views. Adding views with the pushViewController method. You could then use the (NSArray *)popToRootViewControllerAnimated:(BOOL)animated method in the UIViewController class. There is also popToViewController:animated: that will allow you to pop to a specific viewController.
If you are set on using modal views you can implement a protocol in view3 that view2 implements. When you are ready to pop to view1 from view3 you can call [self dismissModalViewControllerAnimated: YES]; then use your protocol to notify view2 that it should also dismiss its modal view.
Hope this helps.
| |
doc_23537773
|
I am trying to add sound effects when a button is pressed.
#import <AudioToolbox/AudioToolbox.h>
- (void)threeBombExplosion
{
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"3Explosions" ofType:@"mp3"];
NSURL *threeExplosionsURL = [NSURL fileURLWithPath:soundPath];
AudioServicesCreateSystemSoundID(CFBridgingRetain(threeExplosionsURL),&_threeExplosionsID);
}
and I am calling this on the function I want it to be executed (UIButton Action).
AudioServicesPlaySystemSound(_threeExplosionsID);
A: Firstly, thats not how you should be calling your mp3 file, you should be using the av audio player object.
NSString *path = [[NSBundle mainBundle] pathForResource:@"3Explosions" ofType:@"mp3"];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
// Create audio player object and initialize with URL to sound
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
Make sure you have strong reference to it, otherwise it might get removed in memory
@property (strong,nonatomic) AVAudioPlayer *audioPlayer;
I would check that the method is being called when the button is being pressed.
If you have a touchupinside action, then your method will be:
-(IBAction)buttonPressed {
[self threeBombExplosion];
}
If that is not working, you should check that the resource is being added to your project, in Xcode you need to make sure you have added it.
In my project i created a subfolder called resources and then an additional one called sounds and placed it neatly in there.
| |
doc_23537774
|
[![enter image description here][1]][1]
As you see, I want to storage my inputs' value from the form:
In my my-app.js:
// Initialize your app
var myApp = new Framework7();
// Export selectors engine
var $$ = Dom7;
// Add views
var view1 = myApp.addView('#view-1');
var view2 = myApp.addView('#view-2', {
// Because we use fixed-through navbar we can enable dynamic navbar
dynamicNavbar: true
});
var view3 = myApp.addView('#view-3');
var view4 = myApp.addView('#view-4');
var ptrContent = $$('.pull-to-refresh-content');
$$('.save-storage-data').on('click', function() {
var storedData = myApp.formStoreData('my-info-form', {
'name': 'John', // this value should be the input's value, I just write for test here
'address':'address', // this value should be the input's value, I just write for test here
'page':'page', // this value should be the input's value, I just write for test here
'tel':'139', // this value should be the input's value, I just write for test here
'email': 'john@doe.com', // this value should be the input's value, I just write for test here
'gender': 'female', // this value should be the input's value, I just write for test here
'isAcceptPushNotification': ['yes'], // this value should be the input's value, I just write for test here
'birthday': '' // this value should be the input's value, I just write for test here
});
alert('success')
});
As you see the $$('.save-storage-data').on('click', function() function is what I want, I want to save the form information to my app.
Additionally, I should judge if all the inputs is filled with value, then save data.
A: Let's loop through all form input fields and check if all of them are filled before saving:
$$('.save-storage-data').on('click', function() {
$$('.save-storage-data input').each(function(i, obj) {
if (!$$(this).val()) {
myApp.alert("Please fill all the required fields.");
return false;
}
});
var storedData = myApp.formStoreData('my-info-form', {
'name': 'John', // this value should be the input's value, I just write for test here
'address':'地址', // this value should be the input's value, I just write for test here
'page':'page', // this value should be the input's value, I just write for test here
'tel':'139', // this value should be the input's value, I just write for test here
'email': 'john@doe.com', // this value should be the input's value, I just write for test here
'gender': 'female', // this value should be the input's value, I just write for test here
'isAcceptPushNotification': ['yes'], // this value should be the input's value, I just write for test here
'birthday': '' // this value should be the input's value, I just write for test here
});
alert('保存成功')
});
| |
doc_23537775
|
I have installed google usb driver from sdk manager.
Now i am trying to connect my Samsung GT-I9300, I can see my device on computer list but eclipse dont open dialog to select device, it is still running application on Emulator virtual device.
I am using Windows 7 Professional with Service Pack 1
Please check screen shots below :
Any help would be highly appreciated !!
Thanks..
EDIT
Now i can see device but i can not select it. Its target is also unknown.
A: download AdbDriverInstaller and install device driver when you connect your device
A: install kies to detect samsung device
http://www.samsung.com/in/support/usefulsoftware/KIES/
A: First, Make the device MTP Connection(Connected as Camera), then reinstall the device driver usuing the following way:
*
*Choose the device from [device manager].
*update driver ----> browse my computer for driver software ----> let me pick from a list... ----> Have Disk.
*Browse and choose the proper driver, the press OK.
*Restart adb.
| |
doc_23537776
|
11-30 21:46:00.822 13943-13943/com.example.user.timetable_test E/SQLiteLog: (1) near "TABLESunday": syntax error
11-30 21:46:00.827 13943-13943/com.example.user.timetable_test D/AndroidRuntime: Shutting down VM
11-30 21:46:00.827 13943-13943/com.example.user.timetable_test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.timetable_test, PID: 13943
android.database.sqlite.SQLiteException: near "TABLESunday": syntax error (code 1): , while compiling: CREATE TABLESunday(_session INTEGER PRIMARY KEY AUTOINCREMENT,_name TEXT,_length INTEGER);
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(near "TABLESunday": syntax error (code 1): , while compiling: CREATE TABLESunday(_session INTEGER PRIMARY KEY AUTOINCREMENT,_name TEXT,_length INTEGER);)
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1058)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:623)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1812)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1743)
at com.example.user.timetable_test.setup.TableDBHandler.onCreate(TableDBHandler.java:43)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.user.timetable_test.setup.TableDBHandler.addEntry(TableDBHandler.java:63)
at com.example.user.timetable_test.setup.SetTable$PlaceholderFragment$1.onClick(SetTable.java:206)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
SQLitDatabase class:
package com.example.user.timetable_test.setup;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.user.timetable_test.MiscData;
public class TableDBHandler extends SQLiteOpenHelper{
private MiscData data = MiscData.getInstance();
private static int DATABASE_VERSION = 1;
private static String DATABASE_NAME = "Timetable.db";
private static String[] TABLE_DAY = new String[MiscData.getInstance().getDays()];
private static String COLUMN_SESSION_NUM = "_session";
private static String COLUMN_NAME = "_name";
private static String COLUMN_LENGTH = "_length";
public TableDBHandler(Context context, SQLiteDatabase.CursorFactory factory){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase){
for(int i = 0; i < data.getDays(); i++){
TABLE_DAY[i] = data.getDay(i + data.getFirstDay());
}
for(int i = 0; i < data.getDays(); i++){
String query = "CREATE TABLE" + TABLE_DAY[i] + "(" + COLUMN_SESSION_NUM +
" INTEGER PRIMARY KEY AUTOINCREMENT " + COLUMN_NAME + " TEXT " +
COLUMN_LENGTH + " INTEGER " + ");";
sqLiteDatabase.execSQL(query);
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1){
sqLiteDatabase.execSQL("DROP TABLE EXISTS" + TABLE_DAY);
onCreate(sqLiteDatabase);
}
public void addEntry(int day, String name, int length){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_LENGTH, length);
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_DAY[day], null, values);
db.close();
}
//get Session length
public int getSessionLength(int day, int session){
int length;
SQLiteDatabase db = getReadableDatabase();
String query =
"SELECT" + COLUMN_LENGTH + "FROM" + TABLE_DAY[day] + "WHERE" + COLUMN_SESSION_NUM +
"=\"" + session + "\";";
Cursor c = db.rawQuery(query, null);
length = c.getInt(c.getColumnIndex(COLUMN_LENGTH));
return length;
}
//get Session name
public String getSessionName(int day, int session){
String name;
SQLiteDatabase db = getReadableDatabase();
String query = "SELECT" + COLUMN_NAME + "FROM" + TABLE_DAY[day] +
"WHERE" + COLUMN_SESSION_NUM + "=\"" + session + "=\";";
Cursor c = db.rawQuery(query, null);
name = c.getString(c.getColumnIndex(COLUMN_NAME));
return name;
}
}
In this code I try to make an array of tables initialized at run-time, this might be where the error comes from or I might be just derping.
Where I add an entry:
tableDBHandler.addEntry(page , sessionSpinners[i].toString(), Integer.parseInt(lengthText[i].getText().toString()));
I have tried changing the data type of COLUMN_LENGTH from TEXT to INTEGER, but this didn't work.
Any ideas how to fix this?
A: The error is into the create of table "TABLESunday": syntax error. There is missing a space on the syntax on your sql code. Try this:
String query = "CREATE TABLE " + TABLE_DAY[i] + "(" + COLUMN_SESSION_NUM +
" INTEGER PRIMARY KEY AUTOINCREMENT " + COLUMN_NAME + " TEXT " +
COLUMN_LENGTH + " INTEGER " + ");";
A: in my case number of "columns names" and "values" not match.
for example
insert INTO cars (car_id,Name) values (v1,v2,v3);
columns number is 2 and values is 3;
A: In my case, I use SQLite to update name of table.
That's all!
A: I am dumb or its my bad, None of the above given solution worked for me, I was creating database on External Storage and the app doesn't had the android.permission.WRITE_EXTERNAL_STORAGE permissions, resolved by granting permission, thanks
| |
doc_23537777
|
There seems to be some debugging protection because main() is not in the bt stack, and I cannot access any of the functions, class-dump-z and IDA Pro both show the functions clearly.
The last two entries in the BT Stack are:
_mh_execute_header<br>
_mh_execute_header<br>
This is where main() should be.
Has anyone seen these before?
From what I have read ptrace() wouldn't let you attach the process but this will let me. I tried to get around sysctl() but I don't think this method has been used either.
Does anyone know what else it could be?
Also I do not have the source files.
A: Your question is exceedingly unclear. What exactly are you asking?
main() is not in the bt stack,
That's quite common for fully-stripped executables. If you run nm a.out | grep main and don't see main, then main can't show up in any stack traces.
That alone does not necessarily prove that the application is using any anti-debugging techniques.
| |
doc_23537778
|
I've been searching for an alternative, and I couldn't seem to find one.
So, how can I check the internet connection in Android Q?
A: Use this code snippet.
@IntRange(from = 0, to = 3)
public static int getConnectionType(Context context) {
int result = 0; // Returns connection type. 0: none; 1: mobile data; 2: wifi
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = 2;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = 1;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
result = 3;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = 2;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = 1;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_VPN) {
result = 3;
}
}
}
}
return result;
}
Add the below permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
A: If you are looking for a simple code, you can use this:
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return cm.getActiveNetwork() != null && cm.getNetworkCapabilities(cm.getActiveNetwork()) != null;
} else {
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
A: The ConnectivityManager only checks whether the smartphone could theoretically establish an Internet connection. Whether an Internet connection actually exists, e.g. if the network quality is very poor, can only be determined with a ping or a web address.
A: Just use this code and call isInternatAvailable(context).
private static final String CMD_PING_GOOGLE = "ping -w -c 1 google.com";
public static boolean isInternetAvailable(@NonNull Context context) {
return isConnected(context) && checkInternetPingGoogle();
}
public static boolean isConnected(@NonNull Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} else {
return false;
}
}
public static boolean checkInternetPingGoogle(){
try {
int a = Runtime.getRuntime().exec(CMD_PING_GOOGLE).waitFor();
return a == 0x0;
} catch (IOException ioE){
EMaxLogger.onException(TAG, ioE);
} catch (InterruptedException iE){
EMaxLogger.onException(TAG, iE);
}
return false;
}
| |
doc_23537779
|
However, I am having difficulties implementing the pattern on Android because of special requirements to the GUI of Android applications:
*
*An Activity may be destroyed at any point (incoming call, user presses home button, ...), and when recreated it should be in the exact same state as when it was left. This is unlike most other GUI applications.
*An Activity can go through many lifecycle states. It may be paused in which case the UI of the Activity should not be modified. If for example some data is being loaded in the background, it cannot be delivered to the View part of MVP (Activity) if it is in a paused state. Again, this is an unusual requirement.
I have read the blog post MVP for Android and looked at the example source code. The end goal I am trying to achieve by using the MVP pattern is to be able to translate all business logic to Objective-C using the transpiler j2objc, such that the business logic can be reused while implementing the same app on iOS.
Is there anyone that have implemented the MVP pattern for Android successfully, and in that case, what am I missing?
A: I suggest implementing the MVP component without involving Activity, perhaps conceptually thinking about what would be useful on both Android and GWT. Create the component using test-driven-development with a mocked View interface, adding tests until the business logic is fully implemented and verified. TDD helps keep the component's API lean (why write tests for stuff you don't need?), which makes porting the component easier.
The Activity requirements you describe can be generalized to be platform-independent: the component should be serializable (small 's', not specifically Java serialization), and needs to accept lifecycle state events. Those, too, can be fully tested using mocks for system features. As you go through this step, you'll likely notice that few of the Activity requirements are necessarily Android-specific, and may be useful on other platforms. Avoid creating huge service APIs; to support serialization, for example, all that's needed are store/load methods, not something like the Parcel API. I've found describing such service APIs to another developer on a whiteboard to be a great way to find unnecessary fluff.
Next, port the component to Android, perhaps by creating an Activity that delegates to the component and provides Android-specific implementation classes for the mocked interfaces. It should all "just work" the first time, but in reality, some requirements may have been missed, so add them to the platform-independent part and repeat.
When you're ready to port to iOS, reimplement those previously mocked interfaces. If these interfaces are lean, it will probably be easier to create them directly in Objective-C, importing the protocol headers generated by j2objc. For example, j2objc's NSDictionaryMap class implements java.util.Map with an NSDictionary implementation -- no need to write and translate a Java version since its just using iOS APIs.
A: I find that the MVP variant Android is built around is a step in the right direction for isolating the business logic in a app. However, if you want to achieve a better separation of concerns, and as a result more reusable domain/business logic, I recommend using the Presenter First pattern (which you briefly mention yourself in the comment). Aside from decreasing coupling it lends itself well to TDD and allows you to unit test all your business logic.
I recently started a GitHub repo with Presenter First examples for Android. Due to the complexity of the Android architecture it's not straightforward to implement the pattern The views tend to be "fatter" than what seems to be acceptable in a normal Presenter First app, mostly because of the activity lifecycle and other oddities as you mention yourself. I've done my best to decouple the business logic from the platform but there's definitely room for improvement. You can find the examples at:
http://github.com/olerass/presenter-first-android
Maybe you can use some ideas from there? Or even better contribute some of your own.
| |
doc_23537780
|
Obviously, you can use the :info command to find all the instances for a type constructor. But what about some complex type expression?
For example, if I wanted to know what instances Maybe Int has (not Maybe, but Maybe Int), how can I do that?
I tried
:info Maybe Int
but that just gives me information for Maybe, followed by information for Int. It's treating it as two separate type constructors, rather than a type expression.
Particularly when you have complicated monad transformer stacks, it's not always obvious exactly which instances a specific stack might have.
| |
doc_23537781
|
android-apt plugin is incompatible with the Android Gradle plugin. Please use 'annotationProcessor' configuration instead.
Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html
But, I have removed all the android-apt Uses from my gradle file.
I tried all the possible solution from stackoverflow and forums. But no-Luck.
Below is my app module's build.gradle
apply plugin: 'com.android.application'
apply plugin: 'realm-android'
apply plugin: 'io.fabric'
apply plugin: 'me.tatarka.retrolambda'
android {
compileSdkVersion 28
buildToolsVersion '28.0.1'
defaultConfig {
applicationId "com.appname.test"
minSdkVersion 19
targetSdkVersion 28
versionCode 24
versionName "1.5.2"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
resValue "string", "AUTH0_DEV_DOMAIN", AUTH0_DEV_DOMAIN
resValue "string", "AUTH0_DEV_CLIENT_ID", AUTH0_DEV_CLIENT_ID
resValue "string", "AUTH0_DEV_SCHEME", AUTH0_DEV_SCHEME
resValue "string", "AUTH0_DEV_AUDIENCE", AUTH0_DEV_AUDIENCE
resValue "string", "AUTH0_PROD_DOMAIN", AUTH0_PROD_DOMAIN
resValue "string", "AUTH0_PROD_CLIENT_ID", AUTH0_PROD_CLIENT_ID
resValue "string", "AUTH0_PROD_SCHEME", AUTH0_PROD_SCHEME
resValue "string", "AUTH0_PROD_AUDIENCE", AUTH0_DEV_AUDIENCE
}
dexOptions {
// incremental true
javaMaxHeapSize "4g"
}
buildTypes {
debug {
buildConfigField "String", "ENDPOINT", "\"https://domine url/\""
ext.alwaysUpdateBuildId = false
}
release {
buildConfigField "String", "ENDPOINT", "\"https://domine url/\""
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
}
/* configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:2.0.1'
}
*/
/*compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}*/
productFlavors {
}
}
retrolambda {
jvmArgs '-noverify'
}
final ANNOTATIONS_VERSION = '28.0.0' //'26.0.0'
final SUPPORT_VERSION = '28.0.0' //'26.0.0'
final RX_JAVA_VERSION = '1.1.6'
final RX_ANDROID_VERSION = '1.2.1'
final BUTTERKNIFE_VERSION = '8.8.1'
final DAGGER_VERSION = '2.2'
final PARCELER_VERSION = '1.1.5'
final DEXTER_VERSION = '2.2.2'
final OTTO_VERSION = '1.3.8'
final ICEPICK_VERSION = '3.2.0'
final TIMBER_VERSION = '4.1.2'
final RETROFIT_VERSION = '2.4.0'
//final PICASSO_VERSION = '2.5.2'
final DEXMAKER_VERSION = '1.2'
final RUNNER_VERSION = '1.0.2' //'0.4'
final ESPRESSO_VERSION = '3.0.2' //'2.2.2'
//////
//final RX_JAVA_VERSION = '1.3.8'
final RX_BINDING_VERSION = '1.0.0' // 2.2.0
//final DAGGER_VERSION = '2.17'
//final PARCELER_VERSION = '1.1.11'
//final DEXTER_VERSION = '5.0.0'
//final TIMBER_VERSION = '4.7.1'
final PICASSO_VERSION = '2.71828'
final MOCKITO_CORE_VERSION = '2.7.22'
dependencies {
// implementation fileTree(include: ['*.jar'], dir: 'libs')
// Support library for android.
implementation "com.android.support:support-annotations:${ANNOTATIONS_VERSION}"
implementation "com.android.support:appcompat-v7:${SUPPORT_VERSION}"
implementation "com.android.support:support-v4:${SUPPORT_VERSION}"
implementation "com.android.support:design:${SUPPORT_VERSION}"
implementation "com.android.support:cardview-v7:${SUPPORT_VERSION}"
implementation "com.android.support:palette-v7:${SUPPORT_VERSION}"
// dependency added to resolve conflict with auth0 customtabs
// dependency using version 25
implementation "com.android.support:customtabs:${SUPPORT_VERSION}"
// Library needed for custom tab views.
//implementation 'com.ogaclejapan.smarttablayout:library:1.6.0@aar'
implementation 'com.ogaclejapan.smarttablayout:library:1.6.1'
// Library for listview and gridview item animations
//implementation 'com.nhaarman.listviewanimations:lib-core:3.1.0@aar'
implementation 'com.nhaarman.listviewanimations:lib-core:3.1.0'
// Library needed for carousel views.
implementation 'com.github.crosswall:Android-Coverflow:release-v1.0.1'
// Library needed for horizontal line progress bar.
implementation 'com.liulishuo.magicprogresswidget:library:1.1.1'
// Library to eliminate findViewById and OnClick events (View injection).
implementation "com.jakewharton:butterknife:${BUTTERKNIFE_VERSION}"
annotationProcessor "com.jakewharton:butterknife-compiler:${BUTTERKNIFE_VERSION}"
// Library which manages the DI throughout android.
implementation "com.google.dagger:dagger:${DAGGER_VERSION}"
annotationProcessor "com.google.dagger:dagger-compiler:${DAGGER_VERSION}"
// compileOnly 'javax.annotation:jsr250-api:1.0'
//compileOnly 'javax.annotation:jsr250-api:1.0-20050927.133100'
// Library that eliminates the boilerplate code of creating Parcelable objects.
implementation "org.parceler:parceler-api:${PARCELER_VERSION}"
annotationProcessor "org.parceler:parceler:${PARCELER_VERSION}"
// Library that eliminates the boilerplate code of granting permissions.
implementation "com.karumi:dexter:${DEXTER_VERSION}"
// Library for reactive java
implementation "io.reactivex:rxjava:${RX_JAVA_VERSION}"
implementation "io.reactivex:rxandroid:${RX_ANDROID_VERSION}"
implementation 'com.cantrowitz:rxbroadcast:1.0.0'
// implementation 'com.cantrowitz:rxbroadcast:2.2.0'
implementation "com.jakewharton.rxbinding:rxbinding:${RX_BINDING_VERSION}"
implementation "com.jakewharton.rxbinding:rxbinding-support-v4:${RX_BINDING_VERSION}"
// Library to be used as an event bus.
implementation "com.squareup:otto:${OTTO_VERSION}"
// Library for efficient logging.
implementation "com.jakewharton.timber:timber:${TIMBER_VERSION}"
// Retrofit library used to manage request asynchronously.
implementation "com.squareup.retrofit2:retrofit:${RETROFIT_VERSION}"
implementation "com.squareup.retrofit2:converter-gson:${RETROFIT_VERSION}"
implementation "com.squareup.retrofit2:adapter-rxjava:${RETROFIT_VERSION}"
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
// Library to load images.
implementation "com.squareup.picasso:picasso:${PICASSO_VERSION}"
// Library for bottom navigation menu.
implementation 'com.roughike:bottom-bar:1.4.0.1'
implementation 'com.ncapdevi:frag-nav:1.0.3'
implementation('cn.trinea.android.view.autoscrollviewpager:android-auto-scroll-view-pager:1.1.2') {
exclude module: 'support-v4'
}
//implementation 'me.relex:circleindicator:1.2.1@aar'
implementation 'me.relex:circleindicator:1.2.2'
implementation 'it.sephiroth.android.library.targettooltip:target-tooltip-library:1.3.15'
// Library for authentication with Auth0.
//implementation 'com.auth0.android:auth0:1.12.1'
implementation 'com.auth0.android:auth0:1.14.1'
// implementation 'com.klinkerapps:link_builder:1.6.1'
implementation 'com.klinkerapps:link_builder:2.0.4'
// Library for ui tag view layout
implementation 'com.github.Cutta:TagView:1.3'
// Library for timeline view
implementation 'com.github.vipulasri:timelineview:1.0.6'
//++ implementation 'com.github.vipulasri:timelineview:1.0.4'
implementation('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
transitive = true;
}
implementation 'com.airbnb:deeplinkdispatch:3.0.0'
annotationProcessor 'com.airbnb:deeplinkdispatch-processor:3.0.0'
testImplementation 'junit:junit:4.12'
// testImplementation 'com.google.truth:truth:0.25'
testImplementation 'com.google.truth:truth:0.42'
testImplementation 'com.squareup.okhttp3:mockwebserver:3.11.0'
testImplementation "org.mockito:mockito-core:${MOCKITO_CORE_VERSION}"
//++ testImplementation 'org.mockito:mockito-core:2.23.0'
testImplementation 'org.robolectric:robolectric:3.4.2'
testImplementation 'org.assertj:assertj-core:3.6.2'
testImplementation 'org.json:json:20180813'
// Support library for android.
androidTestImplementation "com.android.support:support-annotations:${ANNOTATIONS_VERSION}"
// Library for the test runner
androidTestImplementation "com.android.support.test:runner:${RUNNER_VERSION}"
androidTestImplementation "com.android.support.test:rules:${RUNNER_VERSION}"
// not available
// Library for UI testing
androidTestImplementation "com.android.support.test.espresso:espresso-core:${ESPRESSO_VERSION}"
androidTestImplementation "com.android.support.test.espresso:espresso-intents:${ESPRESSO_VERSION}"
// not available
// Library for mocking
androidTestImplementation "com.google.dexmaker:dexmaker:${DEXMAKER_VERSION}"
androidTestImplementation "com.google.dexmaker:dexmaker-mockito:${DEXMAKER_VERSION}"
//androidTestImplementation "org.mockito:mockito-core:${MOCKITO_CORE_VERSION}"
// Library which manages the DI throughout android.
androidTestAnnotationProcessor "com.google.dagger:dagger-compiler:${DAGGER_VERSION}"
testAnnotationProcessor "com.google.dagger:dagger-compiler:${DAGGER_VERSION}"
androidTestImplementation "org.mockito:mockito-android:${MOCKITO_CORE_VERSION}"
implementation files('libs/nineoldandroids-2.4.0.jar')
}
Below is Application level build.gradle
buildscript {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
maven { url 'https://maven.fabric.io/public' }
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
classpath "io.realm:realm-gradle-plugin:1.2.0"
classpath 'io.fabric.tools:gradle:1.22.1'
classpath 'me.tatarka:gradle-retrolambda:3.2.3'
classpath 'me.tatarka:gradle-retrolambda:3.2.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
maven { url "https://jitpack.io" }
maven { url "https://clojars.org/repo/" }
mavenCentral()
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url 'https://maven.fabric.io/public' }
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Can someone please help me to resolve.
My Android studio version is 3.2
I have tried clean, rebuild, invalidate & restart studio, restarts Computer also
| |
doc_23537782
|
php file
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
//get the q parameter from URL
$q=$_GET["q"];
//lookup all links from the xml file if length of q>0
if (strlen($q)>0) {
$hint="";
for($i=0; $i<($x->length); $i++) {
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1) {
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
if ($hint=="") {
$hint="<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
} else {
$hint=$hint . "<br /><a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}
// Set output to "no suggestion" if no hint was found
// or to the correct values
if ($hint=="") {
$response="no suggestion";
} else {
$response=$hint;
}
//output the response
echo $response;
?>
A: My understanding of the issue is that you want to limit the amount of hints returned from the search. You aren't attempting to stop the search but rather to just restrict the output?
The changes which I've made is to turn $hint into an array, then at the bottom of the code it will use array_slice to start at the first position and return $amountToShow. Adding the element to $hint is done with sprintf that's purely for readability sake.
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");
$x = $xmlDoc->getElementsByTagName('link');
//get the q parameter from URL
$q = $_GET["q"];
$hint = [];
//lookup all links from the xml file if length of q>0
if (strlen($q) > 0) {
for ($i = 0; $i < ($x->length); $i++) {
$y = $x->item($i)->getElementsByTagName('title');
$z = $x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType == 1) {
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue, $q)) {
$hint[] = sprintf(
"<a href='%s' target='_blank'>%s</a>",
$z->item(0)->childNodes->item(0)->nodeValue,
$y->item(0)->childNodes->item(0)->nodeValue
);
}
}
}
}
// Set output to "no suggestion" if no hint was found
// or to the correct values
$amountToShow = 10;
if (count($hint) == 0) {
echo "no suggestion";
} else {
echo implode("", array_slice($hint, 0, $amountToShow));
}
| |
doc_23537783
|
Windows Azure Tools: Error: The installed Windows Azure Emulator does not support the role binaries. Please install the latest Windows Azure Emulator and try again.
Windows Azure Tools: The system is missing a prerequisite to execute the service. Please see the release notes.
Is it possible to get 1.7 projects to run using the 2.3 Emulator, or do I need to uninstall the new emulator and re-install the old one? Upgrading the project is currently not an option.
A: SDK 1.8 introduced side-by-side capabilities for the SDK and emulator such that you could have both SDKs installed at the same time. SDK 1.7 did not have this same compatibility so you will not be able to run your SDK 1.7 project on a machine with SDK 2.3 installed.
| |
doc_23537784
|
Is there anyway to disable the double click functionality in the table cell??
Thanks in advance.
A: Technically, the answer is to configure the cellEditor to start editing on single click
DefaultCellEditor editor = (DefaultCellEditor) table.getDefaultEditor(Object.class);
editor.setClickCountToStart(1);
That doesn't help, though - the double click will never reach the table because the first starts editing ;-) Reconsider the user interaction: typically, it's recommended that the second click enhances the action of the first, not that it does something completely different.
| |
doc_23537785
|
<key>UIFileSharingEnabled</key>
<string>YES<string/>
It results in this error: "couldn't parse contents of '/Users/me/Desktop/MyApp/MyApp-Info.plist': Encountered unexpected character s on line 31"
I wrote it after the other keys and before
</dict>
A: change <string/> to </string> and you should be good
| |
doc_23537786
|
So, I have this piece of code...
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th><font color='green'><center>Username</th><th><font color='green'><center>Total EXP</th><th><font color='green'><center>Online Time</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:100px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "hiscores";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT username, overall_xp, onlinetime FROM hs_users ORDER BY overall_xp DESC LIMIT 0, 10");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo "$v";
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
I want to center, and make the result white colored. I've tried it multiple ways, I still can't figure out how to do it.. Could someone help me, please?
I've tried adding font tags and stuff to this part
echo "$v";
Nothing. The outcome is always like this
http://prntscr.com/7q50yi
A: Seems like may some external file is changing the CSS.You can try !important with each style like:
echo "<div style='color:#ffffff !important;text-align:center !important">$v</div>";
use <div> if you eant each row in next line else you can use <span>
| |
doc_23537787
|
<link class="ks-sidebar-dark-style" rel="stylesheet" type="text/css" href="assets/styles/themes/sidebar-black.min.css">
How to put class="ks-sidebar-dark-style" in StyleBundle BundleConfig.cs ?
Current config :
bundles.Add(new StyleBundle("~/bundles/bootstrap").Include(
"~/assets/styles/themes/sidebar-black.min.css"));
A: BundleConfig is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)
To add this file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:
Install-Package Microsoft.AspNet.Web.Optimization
Just create another BundleConfig.cs file under App_Start
Mine looks like this :
using System.Web;
using System.Web.Optimization;
namespace CodeRepository.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Then modify global.asax to look like this :
using System.Web.Optimization;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
| |
doc_23537788
|
For Ex.: 4/7/2016
*
*Day: Monday
Here is my class:
public class Attendance
{
public int Id { get; set; }
public Nullable<System.DateTime> StartDateTime { get; set; }
public Nullable<System.DateTime> EndDateTime { get; set; }
}
When I am trying to do this:
var query = (from t in context.Attendance
select new
{
timeDiff=t.EndDateTime.Value.Subtract(t.StartDateTime.Value).TotalHours,
Day=System.StartDateTime.ToString("dddd");
}).tolist();
Error
LINQ to Entities does not recognize the method 'System.TimeSpan
Subtract(System.DateTime)' method, and this method cannot be
translated into a store expression
I don't want to do like below:
var query = (from t in context.Attendance.toList().
select new
{
timeDiff=t.EndDateTime.Value.Subtract(t.StartDateTime.Value).TotalHours,
Day=System.StartDateTime.ToString("dddd");
}).tolist();
I have Datetime in format like this stored in my tables and so I want expected output like below shown in difference field:
startDatetime Enddatetime Difference
----------------------------------------------------------------
2016-06-29 15:52:32.360 2016-06-29 15:52:36.970 00:00:04
2016-06-29 15:53:32.360 2016-06-29 15:55:36.970 00:2:00
2016-06-29 15:53:32.360 2016-06-29 16:55:36.970 01:02:00
A: You can't use .NET framework specific methods in EF queries unless there's a canonical function defined for them. However there are, for your specific query:
Try:
var query = (from t in context.Attendance
select new
{
TimeDiff=SqlFunctions.DateDiff("hour",t.StartDateTime, t.EndDateTime),
Day=SqlFunctions.DateName("weekday", t.StartDateTime);
}).ToList();
Update
To reflect the changes in the wanted output in your question:
var query = (from t in context.Attendance
select new
{
StartDate = t.StartDateTime,
EndDate = t.EndDateTime,
TimeDiff=SqlFunctions.DateDiff("second",t.StartDateTime, t.EndDateTime),
}).ToList();
And then your can use something like:
foreach(var q in query)
{
Console.Write($"{q.StartDate:d} {q.EndDate:d} {TimeSpan.FromSeconds(q.TimeDiff):c}");
}
| |
doc_23537789
|
I'm trying to convert the first column to rows
So it counts how many users that are speaking a language and using word, excel etc.
I've tried using the pivot but I can't figure out how to use it dynamically.
SELECT *
FROM (
SELECT kolomtellingwaarde,
regeltellingwaarde
FROM analytics_bindingresults
)
pivot
(
count(*)
FOR kolomtellingwaarde IN ('Nederlands', 'Frans')
)
This code works but it only for 2 languages. As you know there are alot of languages so it's kind of impossible to list all the languages in the IN statement. Is there a way that I can create a query that get all the languages and display them as rows('headers'). I've heard it is also possible to use DECODE but I never used that before.
| |
doc_23537790
|
Here's a short clip of the current situation: http://youtu.be/54WXDWxqmXw
I found an implementation example on how to do it over here:
http://www.opengl.org/discussion_boards/showthread.php/174093-GLSL-cube-shadows-projecting?p=1219162&viewfull=1#post1219162
It seemed fairly easy to understand, so I figured this would be a great way to start off with, but I'm having some difficulties with the matrices (As shown in the video above).
My Vertex Shader:
#version 330 core
layout(std140) uniform ViewProjection
{
mat4 V;
mat4 P;
};
layout(location = 0) in vec3 vertexPosition;
layout(location = 1) in vec2 vertexUV;
out vec2 UV;
out vec4 posCs;
uniform mat4 M;
uniform mat4 lightView;
void main()
{
mat4 MVP = P *V *M;
gl_Position = MVP *vec4(vertexPosition,1);
UV = vertexUV;
posCs = V *M *vec4(vertexPosition,1);
}
Fragment Shader:
#version 330 core
in vec2 UV;
in vec4 posCs;
out vec4 color;
// Diffuse texture
uniform sampler2D renderTexture;
uniform samplerCubeShadow shadowCubeMap;
uniform mat4 lightView;
uniform mat4 lightProjection;
uniform mat4 camViewInv;
void main()
{
color = texture2D(renderTexture,UV).rgba;
mat4 lView = mat4(1); // The light is currently at the world origin, so we'll skip the transformation for now (The less potential error sources the better)
vec4 posLs = lView *camViewInv *posCs;
vec4 posAbs = abs(posLs);
float fs_z = -max(posAbs.x,max(posAbs.y,posAbs.z));
vec4 clip = lightProjection *vec4(0.0,0.0,fs_z,1.0);
float depth = (clip.z /clip.w) *0.5 +0.5;
vec4 r = shadowCube(shadowCubeMap,vec4(posLs.xyz,depth));
color *= r;
}
(I've only posted the relevant parts)
lightProjection is the same projection matrix that I've used to render the scene into the cubemap.
I'm not entirely sure about 'camViewInv', from the example I've linked above I came up with this:
glm::mat4 camViewInv(
camView[0][0],camView[1][0],camView[2][0],0.0f,
camView[0][1],camView[1][1],camView[2][1],0.0f,
camView[0][2],camView[1][2],camView[2][2],0.0f,
camPos[0],camPos[1],camPos[2],1.0f
);
camView being the camera's view matrix, and camPos the camera's worldspace position.
Everything else should be self-explanatory I believe.
I can't see anything wrong with the shaders, but I'm fairly certain the scene is rendered correctly to the cubemap (As shown in the video above). Maybe someone more versed than me can spot the issue.
// Update:
Some additional information about the creation / usage of the shadow cubemap:
Creating the cubemap texture:
unsigned int frameBuffer;
glGenFramebuffers(1,&frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER,frameBuffer);
unsigned int texture;
glGenTextures(1,&texture);
glBindTexture(GL_TEXTURE_CUBE_MAP,texture);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_COMPARE_FUNC,GL_LEQUAL);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_R,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_COMPARE_MODE,GL_COMPARE_R_TO_TEXTURE);
for(int i=0;i<6;i++)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X +i,0,GL_DEPTH_COMPONENT,size,size,0,GL_DEPTH_COMPONENT,GL_FLOAT,0);
glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_CUBE_MAP_POSITIVE_X +i,texture,0);
glDrawBuffer(GL_NONE);
}
The light's matrices:
glm::perspective<float>(90.f,1.f,2.f,m_distance); // Projection Matrix
// View Matrices
glm::vec3 pos = GetPosition(); // Light worldspace position
glm::lookAt(pos,pos +glm::vec3(1,0,0),glm::vec3(0,1,0));
glm::lookAt(pos,pos +glm::vec3(-1,0,0),glm::vec3(0,1,0));
glm::lookAt(pos,pos +glm::vec3(0,1,0),glm::vec3(0,0,-1))
glm::lookAt(pos,pos +glm::vec3(0,-1,0),glm::vec3(0,0,1))
glm::lookAt(pos,pos +glm::vec3(0,0,1),glm::vec3(0,1,0))
glm::lookAt(pos,pos +glm::vec3(0,0,-1),glm::vec3(0,1,0))
Vertex Shader:
#version 330 core
layout(location = 0) in vec4 vertexPosition;
uniform mat4 shadowMVP;
void main()
{
gl_Position = shadowMVP *vertexPosition;
}
Fragment Shader:
#version 330 core
layout(location = 0) out float fragmentDepth;
void main()
{
fragmentdepth = gl_FragCoord.z;
}
A: I would suggest doing this in world space, light positions are typically defined in world space and it will reduce the workload if you keep it that way. I removed a bunch of uniforms that you do not need if you do this in world space.
Compute lighting direction and depth in vtx. shader:
#version 330 core
layout(std140) uniform ViewProjection
{
mat4 V;
mat4 P;
};
layout(location = 0) in vec4 vertexPosition; // W is automatically assigned 1, if missing.
layout(location = 1) in vec2 vertexUV;
out vec2 UV;
out vec4 lightDirDepth; // Direction = xyz, Depth = w
uniform mat4 M;
uniform vec3 lightPos; // World Space Light Pos
uniform vec2 shadowZRange; // Near / Far clip plane distances for shadow's camera
float vecToDepth (vec3 Vec)
{
vec3 AbsVec = abs (Vec);
float LocalZcomp = max (AbsVec.x, max (AbsVec.y, AbsVec.z));
const float n = shadowZRange [0]; // Near plane when the shadow map was built
const float f = shadowZRange [1]; // Far plane when the shadow map was built
float NormZComp = (f+n) / (f-n) - (2.0*f*n)/(f-n)/LocalZcomp;
return (NormZComp + 1.0) * 0.5;
}
void main()
{
mat4 MVP = P *V *M;
gl_Position = MVP *vertexPosition;
UV = vertexUV;
vec3 lightDir = lightPos - (M *vertexPosition).xyz;
float lightDepth = vecToDepth (lightDir);
lightDirDepth = vec4 (lightDir, lightDepth);
}
Modified Fragment Shader (sample cubemap using light dir, and test against depth):
#version 330 core
in vec2 UV;
in vec4 lightDirDepth; // Direction = xyz, Depth = w
out vec4 color;
// Diffuse texture
uniform sampler2D renderTexture;
uniform samplerCubeShadow shadowCubeMap;
void main()
{
const float bias = 0.0001; // Prevent shadow acne
color = texture (renderTexture,UV).rgba;
float r = texture (shadowCubeMap, vec4 (lightDirDepth.xyz, lightDirDepth.w + bias));
color *= r;
}
I added two new uniforms:
*
*lightPos -- World space position of your light
*shadowZRange -- The values of your near and far plane when you built your shadow cube map, packed into a vec2
Let me know if you need me to explain anything or if this does not produce meaningful results.
| |
doc_23537791
|
I wanna search it by click a button , and the system auto according to "today",and choose the day "after one month" for example now is 11/26/2013 , by clicking the button , the system will choose the data dated 12/26/2013 and pump a msg out.
here is my code , i just wanna store today "day" into a variable and start searching
Sub Macro1()
'
Dim oldDate As Date
Dim oldDay As Integer
' Assign a date using standard short format.
oldDate = 2 / 12 / 1969
oldDay = Microsoft.VisualBasic.DateAndTime.Day(oldDate)
' oldDay now contains 12.
Selection.Formula = ""
Range("H1").Select
Sheets("Pipeline").Select
Cells.Find(What:=oldDay, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
End Sub
and the system said the object missed.
please kindly help
A: I am not sure if this is what you want but try it
Sub Main()
Dim cell As Range
For Each cell In Range("H1:H" & Range("H" & Rows.Count).End(xlUp).Row)
If cell = DateAdd("m", 1, Left(Now, 10)) Then
MsgBox "Cell matches 1 month from today at " & cell.Address
End If
Next
End Sub
| |
doc_23537792
|
Cross origin requests are only supported for HTTP. dojo.js.uncompressed.js:308
req.getText dojo.js.uncompressed.js:308
injectModule dojo.js.uncompressed.js:1522
doRequire dojo.js.uncompressed.js:6703
dojo.require dojo.js.uncompressed.js:6740
(anonymous function) index.html:63
Does anyone encounter this problem?
My application looks like this
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" href="js/dojo-1.9.1/dojox/mobile/themes/android/android.css" type="text/css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script type="text/javascript" src="js/dojo-1.9.1/dojo/dojo.js.uncompressed.js" djConfig="parseOnLoad:true">
<title>Hello World</title>
</head>
<body>
<!-- ACCIDENT TOOLKIT PAGE -->
<div dojoType="dojox.mobile.View" id="accHelp" selected="true">
<h1 dojoType="dojox.mobile.Heading">Accident</h1>
<div class="text">If you are in an accident, you should first move to a safe
location. Below are some additional actions you can take:</div>
<ul dojoType="dojox.mobile.RoundRectList">
<li dojoType="dojox.mobile.ListItem"
onclick="window.location='geo:0,0?q=police';">Call the Police</li>
<li dojoType="dojox.mobile.ListItem"
onclick="window.location='geo:0,0?q=towing';">Call for a Tow Truck</li>
<li dojoType="dojox.mobile.ListItem" moveTo="accInfo" transition="slide"
onClick="itemClicked();">Exchange Driver Info</li>
<li dojoType="dojox.mobile.ListItem" moveTo="accInfo" transition="slide"
onClick="itemClicked();">Record Accident Location</li>
<li dojoType="dojox.mobile.ListItem" moveTo="accInfo" transition="slide"
onClick="itemClicked();">Take Photos of Accident</li>
</ul>
</div>
<!-- EXCHANGE DRIVER INFO PAGE -->
<div dojoType="dojox.mobile.View" id="accInfo">
<h1 dojoType="dojox.mobile.Heading" back="Accident" moveTo="accHelp"
onClick="console.log('Going back');">Driver</h1>
<h2 dojoType="dojox.mobile.RoundRectCategory">Other Driver Info</h2>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
dojo.require("dojox.mobile.parser");
dojo.require("dojox.mobile");
</script>
<script type="text/javascript">
app.initialize();
function itemClicked() {
console.log("itemClicked()");
}
</script>
</body>
</html>
A: Have you tried with the brand new released Cordova 3.1? With a bit of luck this might fix the problem.
A: After days of debugging, I have finally found the problem, it is due to some of dojo javascript file name starts with underscore _ . Apparently it is a known problem in Android webkit where it refuses to load any filename starts with a underscore from the local file system.
The workaround is to use dojo build.
| |
doc_23537793
|
I'm trying to use GoToStateAction to change the state with a DataTriggerBehavior, but it doesn't work and I have no idea how to debug it :(
I'm guessing that it is an issue with Interaction in a style, as I also tried changing the DataTriggerBehavior to an EventTriggerBehavior and that didn't fire either.
The Style:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
xmlns:eim="using:Microsoft.Xaml.Interactions.Media"
xmlns:vm="using:Test.ViewModel">
<Style x:Key="AppBarBtnStyle" TargetType="AppBarButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="AppBarButton">
<Border x:Name="bord" CornerRadius="12" Background="Gray" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="4">
<Grid x:Name="Root" MinWidth="{TemplateBinding MinWidth}" MaxWidth="{TemplateBinding MaxWidth}" Background="{TemplateBinding Background}">
<i:Interaction.Behaviors>
<core:DataTriggerBehavior Binding="{Binding FlashControl}" ComparisonCondition="Equal" Value="{TemplateBinding Name}" >
<core:GoToStateAction StateName="Flash"/>
</core:DataTriggerBehavior>
</i:Interaction.Behaviors>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Flash">
<Storyboard>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="Root" Storyboard.TargetProperty="(Root.BorderBrush).(SolidColorBrush.Color)" EnableDependentAnimation="True" Duration="0:0:1" RepeatBehavior="Forever" AutoReverse="False">
<DiscreteColorKeyFrame Value="Red" KeyTime="0:0:0"/>
<DiscreteColorKeyFrame Value="Blue" KeyTime="0:0:0.75"/>
<DiscreteColorKeyFrame Value="Red" KeyTime="0:0:1"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The Binding Property:
Private mFlashControl As String
Public Property FlashControl() As String
' The Name of the Control to Flash
Get
Return mFlashControl
End Get
Set(value As String)
SetProperty(mFlashControl, value)
End Set
End Property
The Button:
<AppBarButton x:Name="myButton" Style="{StaticResource AppBarBtnStyle}" Icon="Clock"/>
So if I set the FlashControl Property to "myButton", all the Buttons with that Style will run the DataTriggerBehavior to check if their Name Property matches that of FlashControl.
If a match is found then the VisualState of the Button will be changed and run the flash Storyboard.
| |
doc_23537794
|
int main (int argc, char **argv)
{
char user [10];
char *path = argv[1];
int result;
const char *filename = "/home/guima/TP1/Users";
result = access (filename, F_OK);
int fd;
fd = open(argv[1], O_RDONLY);
if (result == 0)
{
unlink(argv[1]);
write(1,"Deleted!\n\n", 35);
}
else
{
write(1,"Error!\n\n",30);
}
close(fd);
return 0;
}
| |
doc_23537795
|
function ucFirst(str) {
var newStr = str.charAt(0).toUpperCase();
for (var i = 1; i < str.length; i++) {
newStr += str.charAt(i);
}
return newStr
}
alert(ucFirst("john"));
this will print out "John" along with an undefined in the console.
Now I tried the exact same thing using the array values
function ucFirst(str) {
var newStr = str.str[0].toUpperCase();
for (var i = 1; i < str.length; i++) {
newStr += str.str[i];
}
return newStr;
}
alert(ucFirst("john"));
I get this error in console "Cannot read property '0' of undefined"
Why is it so?
A: str.str[0].toUpperCase();
should just be
str[0].toUpperCase();
If that isn't the case, you should try console.log(str) and find out what exactly str is but I believe this is your problem.
A: It works. Replace all instances of str.str[ with str[
It reads out undefined because you're calling your string in object context and trying to refer to a property str, which is not a property, thus undefined. There is no String.str on the class object, nor is there a str.str on your string object (object used loosely) that you're passing.
Note: I want to add that while doing the replacement will fix your code, this is not the most optimal way to apply a propercase casting.
| |
doc_23537796
|
CREATE TABLE [GenContents]
(
[Id] INT NOT NULL IDENTITY (1,1),
[ModuleUniqueName] NVARCHAR(4000) NOT NULL,
[ResponseContent] NTEXT,
[Category] NVARCHAR(4000) NOT NULL,
[Language] NVARCHAR(4000) NOT NULL,
[StoredTime] NVARCHAR(4000) NOT NULL
);
ALTER TABLE [GenContents] ADD CONSTRAINT [PK_GenContents] PRIMARY KEY ([Id]);
| |
doc_23537797
|
I managed to write some queries that for example check if the username that is entered in my RN app matches the one that is on the DB and returns its userID.
I know that on my DB every User has its Password that is being stored inside the DB in a hashed way.
How would a Query look like that would return for example the userID as I am doing it but only if the username exists and it matches the Password that is stored on the DB?
Do I need to know how the passwords are hashed on the DB?
The Query for userid:
static getUserId (username, callback) {
db.query(`SELECT userid FROM employee WHERE username = '${username}'`, (err, res)=> {
if(err.error){
return callback(err.error)
} else {
return callback(res)
}
})
}
The passwords are saved in the same employee table under password.
EDIT: I think I can take two WHERE statements like this:
`SELECT userid FROM employee WHERE username = '${username}' AND WHERE password = '${password}'`
but if a User enters his password inside the app it is not hashed so do I need to send the same hash method to compare these values?
Thanks in advance!
Best regards Faded.
A: You can use bcrypt.js for hashing your passwords.
To hash password in SignUp.js:
app.post('/signup',(req,res,next)=> {
//Password from request body of register request
const myPlaintextPassword = req.body.password
//saltRounds are typically set to 12
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB with INSERT.
});
}
Now to compare with Hash in Login.js:
app.post('/login',async (req,res,next)=>{
const existingUser = await db.query(`SELECT userid FROM employee WHERE username = '${username}'`, (err, res)=> {
if(err.error){
return callback(err.error)
} else {
return callback(res)
}
})
const valid = await bcrypt.compare(req.body.password, existingUser.password);
if (!valid) {
res.status(401).send('Wrong pass');
return req.next()
}
}
A: You need to hash the incoming password and compare the two hashes.
That being said: if this is going to be at all used by real people I would suggest using a library to handle your auth instead of writing your own. There are a lot of things that can go wrong to make your application insecure.
| |
doc_23537798
|
CarsB cars = CarsB(lastname: 'Uysal', firstname: 'Kerem');
print(cars.firstname);
}
class Cars {
String firstname = '';
String lastname = '';
int yas = 0;
Cars(
this.yas, {
this.firstname = '',
this.lastname = '',
});
}
class CarsB extends Cars {
CarsB({String firstname = '', String lastname = ''})
: super(yas, firstname: firstname, lastname: lastname);
}
Why am I getting an error?
Error is:
Error: Undefined name 'yas'.
main.dart:51
: super(yas, firstname: firstname, lastname: lastname);
^^^
Exited (254)
A: CarsB({String firstname = '', String lastname = ''})
: super(yas, firstname: firstname, lastname: lastname);
Your CarsB constructor does not have a parameter called yas. So passing yas to the super constructor is a mistake. The compiler does not know what to do with it. When I call final b = CarsB(firstname: 'John', lastname: 'Doe'); what do you expect yas to be? It is undefined. And your compiler cannot compile that.
| |
doc_23537799
|
1 city1 85 100 0.05
2 city2 80 100 0.05
3 city3 34 100 0.32
I want to return a list of tuples representing the lines in the file.
The items should be of type int except for the name string
and the weight float
So the result would be like this:
[(1, 'city1', 85, 100, 0.05), (2, 'city2', 80, 100, 0.05), (3, 'city3', 34, 100, 0.32)]
This is the code that I have until now:
def reader(filename):
with open(filename) as f:
arr = [tuple(line.split()) for line in f]
return arr
print(reader("sample.txt"))
And the result is as follows:
[('1', 'city1', '85', '100', '0.05'), ('2', 'city2', '80', '100', '0.05'), ('3', 'city3', '34', '100', '0.32')]
As you can see all the items are strings but I want to put the numbers as int and the float numbers as float just like it appears above but I´m stuck and I don´y know what to do.
Can you help me please?
Thannks for advanced.
Greetings
A: You can zip with the corresponding type, and use it to convert from the string.
def reader(filename):
types = [int, str, int, int, float]
with open(filename) as f:
return [tuple(t(x) for t, x in zip(types, line.split())) for line in f]
A: def convert(x):
try:
a = float(x)
b = int(a)
return b if a == b else a
except:
return x
def reader(filename):
lines = []
with open(filename) as f:
for l in f:
lines.append(tuple(map(convert, l.split())))
return lines
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.